diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 400a819442..058705ce29 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -13,27 +13,27 @@ on: workflow_dispatch: permissions: contents: read -env: - CARGO_TERM_COLOR: always - CARGO_INCREMENTAL: 0 +# A newer push to a PR branch cancels its older run. +concurrency: + group: print-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + # Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache + # but never save one; a manual run on main saves the cache they restore. windows: - runs-on: windows-2022 - timeout-minutes: 90 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f # master - with: - toolchain: stable - components: clippy - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - key: desktop-print - - run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings - - run: cargo test --locked -p vectorcraft - - name: Check pending submission and queue refusal feedback - shell: bash - # A filter that matches nothing still passes, so fail unless some test ran. - run: | - cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee printps.log - grep -Eq 'test result: ok\. [1-9][0-9]* passed' printps.log || { echo "::error::tests::printps matched no tests"; exit 1; } + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["windows-2022"]' + timeout-minutes: 90 + # As before: printing builds and tests without craft-fonts, nextest or the wasm target. + craft-fonts-ref: "" + tools: "" + targets: "" + # A filter that matches nothing still passes, so the printps run fails unless some test ran. + command: | + cargo clippy --locked -p vectorcraft --all-targets -- -D warnings + cargo test --locked -p vectorcraft + log="$RUNNER_TEMP/printps.log" + cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log" + grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1677e538c..07b3c6b7fe 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -63,6 +63,7 @@ jobs: needs: git-sources permissions: contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 7fc9b59251..b121ce45f1 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -27,8 +27,8 @@ permissions: jobs: windows-arm64: - # Immutable supporting workflow revision until the new install contract lands upstream. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f + # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main with: app-name: vectorcraft app-dir: VectorCraft diff --git a/AGENTS.md b/AGENTS.md index 61f141079e..0d33612d5c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - Creative Commons with redistribution allowed. - **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`. - `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset. - - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo** (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. + - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. - Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft. - Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it. - Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets. @@ -46,7 +46,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. +- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`). ## Running and looking at the app @@ -59,7 +59,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`). ## Roadmap and progress docs -The progress docs follow craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md): +The progress docs: - [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log. - [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships). - [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus. @@ -72,17 +72,19 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit ## Contributor credits (About window) - About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json` - (commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for + (commit stats; never hand-edit) and `contributors/people.toml` (names people chose for themselves). See `docs/contributors.md`. - **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once whether they want to be credited by more than their username: a real name, a display name, and/or their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry - (copy the template at the top of the file, or run - `python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`) + (copy the template at the top of the file) and include it in their PR, committed as them. If no, change nothing: they are credited as `@username` anyway. - Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or GitHub profiles). Never hand-edit `contributors.json`. -- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also - re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/ASSETS.md b/ASSETS.md index 26d4630911..3233c99d0e 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -6,7 +6,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`). -**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts) (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). The small Latin UI/document fonts below predate that rule and stay. +**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. **Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. @@ -345,6 +345,9 @@ Generated-in-code art is original and has no file to list. This covers the defau | `examples/ribbons.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/feature-sheet.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/perspective-city.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | +| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` | +| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` | +| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` | ## Assets embedded by the PDF backend diff --git a/CLAUDE.md b/CLAUDE.md index 0460b61925..17783d9a1f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,7 +28,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - Creative Commons with redistribution allowed. - **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`. - `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset. - - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo** (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. + - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. - Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft. - Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it. - Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets. @@ -47,7 +47,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). - **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). -- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. +- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`). ## Running and looking at the app @@ -60,7 +60,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`). ## Roadmap and progress docs -The progress docs follow craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md): +The progress docs: - [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log. - [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships). - [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus. @@ -69,3 +69,8 @@ The progress docs follow craftrules' [`standards/progress-docs.md`](https://gith When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history. - Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated. - Keep the README's Status section in step with the ROADMAP headline. + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/Cargo.lock b/Cargo.lock index 78306baae3..01b2e0e815 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -303,7 +303,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -334,7 +334,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -360,7 +360,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -665,7 +665,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "tracing", ] @@ -688,7 +688,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop 0.14.5", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-client", ] @@ -705,6 +705,17 @@ dependencies = [ "shlex", ] +[[package]] +name = "cfb" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f13298d9178622b7916ec5d01d470425c04273c8ed07e87b1c38b34c4f4612b" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -763,9 +774,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -1017,7 +1028,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13af dependencies = [ "craft-winprint-gdi", "miniz_oxide 0.9.1", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "tempfile", "winprint", "winsafe", @@ -1047,13 +1058,14 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", "semver", @@ -1069,6 +1081,17 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-vectorcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=14d5dbb50c317b8747a9cf9eb35ab8a22515f137#14d5dbb50c317b8747a9cf9eb35ab8a22515f137" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-window" version = "0.1.0" @@ -1887,7 +1910,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -1939,6 +1962,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + [[package]] name = "gif" version = "0.14.2" @@ -2232,7 +2265,7 @@ dependencies = [ "rustc-hash 2.1.3", "smallvec", "stringprep", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -2608,14 +2641,14 @@ dependencies = [ "bytemuck", "byteorder-lite", "color_quant", - "gif", + "gif 0.14.2", "image-webp", "moxcms", "num-traits", "png 0.18.1", "tiff", - "zune-core", - "zune-jpeg", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", ] [[package]] @@ -2836,7 +2869,7 @@ dependencies = [ "bumpalo", "flate2", "float-cmp", - "gif", + "gif 0.14.2", "image-webp", "imagesize 0.14.0", "indexmap", @@ -2851,7 +2884,7 @@ dependencies = [ "tiny-skia-path 0.12.0", "xmp-writer", "yoke", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -3899,7 +3932,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -4379,12 +4412,15 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" dependencies = [ + "gif 0.13.3", + "image-webp", "log", "pico-args", "rgb", "svgtypes 0.15.3", "tiny-skia", "usvg 0.45.1", + "zune-jpeg 0.4.21", ] [[package]] @@ -4445,9 +4481,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "roxmltree" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ "memchr", ] @@ -4488,9 +4524,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -5096,9 +5132,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" dependencies = [ "serde", ] @@ -5141,7 +5177,7 @@ dependencies = [ "libc", "log", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "wayland-backend", "wayland-client", @@ -5416,7 +5452,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -5489,7 +5525,7 @@ dependencies = [ "half", "quick-error 2.0.1", "weezl 0.1.12", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -5992,7 +6028,7 @@ dependencies = [ "kurbo 0.13.1", "log", "pico-args", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "simplecss", "siphasher", "skrifa 0.44.0", @@ -6036,7 +6072,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.18.0" +version = "0.20.0" dependencies = [ "arboard", "block2 0.6.2", @@ -6061,8 +6097,10 @@ dependencies = [ "raw-window-handle", "rfd", "serde_json", + "smithay-clipboard", "socket2", "vectorcraft-engine", + "vectorcraft-render", "vectorcraft-text", "vectorcraft-ui-egui", "wayland-backend", @@ -6079,7 +6117,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.18.0" +version = "0.20.0" dependencies = [ "crc32fast", "flate2", @@ -6090,7 +6128,7 @@ dependencies = [ [[package]] name = "vectorcraft-brush" -version = "0.18.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "serde", @@ -6102,7 +6140,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.18.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6118,7 +6156,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.18.0" +version = "0.20.0" dependencies = [ "log", "objc2-core-foundation", @@ -6140,7 +6178,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.18.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -6152,7 +6190,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.18.0" +version = "0.20.0" dependencies = [ "chrono", "hayro-ccitt", @@ -6166,12 +6204,12 @@ dependencies = [ "tiff", "vectorcraft-color", "vectorcraft-geom", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] name = "vectorcraft-effects" -version = "0.18.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6187,17 +6225,19 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.18.0" +version = "0.20.0" dependencies = [ + "cfb", "craft-docpath", "crc32fast", "flate2", + "hayro-jpeg2000", "image", "kurbo 0.13.1", "log", "proptest", - "roxmltree 0.21.1", - "rustix 1.1.5", + "roxmltree 0.21.2", + "rustix 1.1.6", "ruzstd", "serde", "serde_json", @@ -6226,7 +6266,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.18.0" +version = "0.20.0" dependencies = [ "fax", "flate2", @@ -6250,11 +6290,12 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.18.0" +version = "0.20.0" dependencies = [ + "craft-vectorcraft-format", "flate2", "proptest", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_json", "thiserror 2.0.21", @@ -6265,7 +6306,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.18.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -6277,7 +6318,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.18.0" +version = "0.20.0" dependencies = [ "image", "log", @@ -6296,7 +6337,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.18.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6310,7 +6351,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.18.0" +version = "0.20.0" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -6322,7 +6363,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.18.0" +version = "0.20.0" dependencies = [ "aes", "chrono", @@ -6335,7 +6376,7 @@ dependencies = [ "kurbo 0.13.1", "log", "md-5", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "serde", "serde_json", "sha2", @@ -6354,7 +6395,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.18.0" +version = "0.20.0" dependencies = [ "serde", "serde_json", @@ -6368,10 +6409,10 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.18.0" +version = "0.20.0" dependencies = [ "flate2", - "gif", + "gif 0.14.2", "image", "jpeg-encoder", "log", @@ -6380,6 +6421,7 @@ dependencies = [ "psd", "serde_json", "tiff", + "unicode-general-category", "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", @@ -6397,14 +6439,14 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.18.0" +version = "0.20.0" dependencies = [ "proptest", ] [[package]] name = "vectorcraft-svg" -version = "0.18.0" +version = "0.20.0" dependencies = [ "craft-docpath", "flate2", @@ -6429,7 +6471,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.18.0" +version = "0.20.0" dependencies = [ "fax", "image", @@ -6447,7 +6489,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.18.0" +version = "0.20.0" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -6468,7 +6510,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.18.0" +version = "0.20.0" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -6476,12 +6518,13 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.18.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", "serde", "serde_json", + "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", @@ -6492,7 +6535,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.18.0" +version = "0.20.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6504,7 +6547,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.18.0" +version = "0.20.0" dependencies = [ "bytemuck", "craft-keymap", @@ -6515,7 +6558,7 @@ dependencies = [ "egui_kittest", "image", "log", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_json", "toml", @@ -6542,7 +6585,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.18.0" +version = "0.20.0" dependencies = [ "eframe", "egui", @@ -6808,7 +6851,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -6821,7 +6864,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -6843,7 +6886,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -7518,7 +7561,7 @@ dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -7577,7 +7620,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -7619,7 +7662,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -7673,7 +7716,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.18.0" +version = "0.20.0" dependencies = [ "serde_json", ] @@ -7723,7 +7766,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -7907,9 +7950,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.0" +version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ "crc32fast", "flate2", @@ -7946,19 +7989,34 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + [[package]] name = "zune-core" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + [[package]] name = "zune-jpeg" version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ - "zune-core", + "zune-core 0.5.3", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index c134a3c19d..1876edbf7a 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.18.0" +version = "0.20.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -19,7 +19,10 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "14d5dbb50c317b8747a9cf9eb35ab8a22515f137" } +# craft-update: app-specific pretend versions apply to startup and manual checks. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/README.md b/README.md index fd45eb9cdd..8a3c453c5c 100644 --- a/README.md +++ b/README.md @@ -205,10 +205,10 @@ drag-and-drop, set **Preferences › Performance › Linux Display Server** to * the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayland, where drops work (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). -On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's -pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its -pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use -XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with +On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft can't get a drawing tablet's pen +input on native Wayland yet (#491, #2028). When a pen is attached as VectorCraft starts, the window opens through +XWayland, where the pen works as a mouse and the app reads its pressure (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps +Wayland). For a pen attached later, set the same preference to **X11 (XWayland)** and restart, or start the app with `WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). ### Use it from Claude Code and other agents @@ -328,12 +328,21 @@ stand on its own. | | App | What it's for | Code | Learn more | |:-:|---|---|---|---| | | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | -| | **VectorCraft** | **Vector illustration · you are here** | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | +| | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | | | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | | | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. diff --git a/ROADMAP.md b/ROADMAP.md index 8231428eeb..4d5918cba5 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-23 · **Change:** minor (OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; 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 @@ -110,6 +110,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Japanese | `ja` | full | 100% | | German | `de` | full | 98% | | Korean | `ko` | full | 100% | +| Bosnian | `bs` | full (AI-assisted, native review pending) | 100% | | Vietnamese | `vi` | full | 100% | Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending). @@ -128,6 +129,17 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). +- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). +- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). +- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. +- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. +- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. +- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. +- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. +- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. +- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). - 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. - 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn. - 2026-10-23: COLR colour fonts (v0 and v1, as in Noto Color Emoji's vector build, Segoe UI Emoji, Nabla) draw as vector art: their layers' colours, gradients, clips and blend modes on the canvas and in SVG, EPS, legacy `.ai` and PDF, and as editable paths with Create Outlines; glyphs using sweep gradients or compositing modes are drawn as images of the glyph. @@ -144,6 +156,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | Date | What landed | |---|---| +| 2026-10-29 | Linux: the Flatpak on GNOME copies and pastes text with other apps through the compositor's core Wayland protocol (smithay-clipboard on the window's connection), where arboard has neither data-control nor X11. Scores and estimates unchanged. | +| 2026-10-29 | Linux: a clipboard that can't be opened (the Flatpak on GNOME, where arboard has neither data-control nor X11) is retried after 1 s, doubling to a minute, and logged once, where the background Paste check used to reconnect and log a warning every 250 ms (267k warnings in 18 h). Scores and estimates unchanged. | | 2026-10-21 | 3D lighting: four original lighting presets shared by Revolve, Extrude & Bevel, Inflate and Rotate, with command access and manual Custom settings; scores and estimates unchanged. | | 2026-10-21 | Print: the Print dialog's Media list has the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5 (which keep their ISO 216 dimensions for settings saved before them), はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm / 長形4号 90 × 225 mm / 角形2号 240 × 332 mm / 角形3号 216 × 277 mm and 四六判 127 × 188 mm. A paper is named by its JSON id or its dialog label, any case and spacing (`B5 (JIS)` or `b5jis`), and every added size prints as its own PDF page size. 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. | @@ -182,7 +196,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | 2026-10-12 | Graphs: Object › Graph › Design… and Marker… (designs with a preview, New Design, Rename, Delete Design, Paste Design, Select Unused, and markers drawn with a design or None) (#1092); Graph Data opens as a worksheet with Import Data…, column width and decimals (#1138), and takes Transpose, Switch x/y, `|` line breaks in labels and the pie Legend, Position and Sort options (#1115); Graph Type adds Add Drop Shadow and Add Legend Across Top (#1119), widths past 100%, First Row and First Column in Front, and Draw Filled Lines (#1136); graphs keep their label formatting when drawn again (#1137). Align: a Horizontal & Vertical Align Center button (#1073); Align to Key Object makes the topmost selected object the key (#1221), and the palette's key entry reads Cancel Key Object (#1224). Pen: the nearest end wins over snapping, Alt on the last anchor edits it, and Enter, Escape or a tool switch finish a handle preview as one undo step (#821). Direct Selection: a click on an anchor of an already selected path selects that anchor alone (#1237). Make Compound Path keeps the backmost object's paint, and a selected member reads and changes the compound's fill rule (#1225). Shape Builder and Live Paint no longer turn a line's loose end past a crossing into a piece that runs out and back (#1230). Art moved or duplicated with an artboard follows Transform Pattern Tiles (#1219). A click with the Rectangular Grid tool opens its options dialog (#1169). Commands that change nothing (Lock, Hide, Transform Each, Rearrange Artboards and others) add no undo step (#1233). Saving with missing placed files keeps their relink data, and .ai export honours the chosen artboards (#718). SVG export keeps Unicode data-attribute names, and SVG Options refuses an invalid artboard range (#989). CMYK colours given in percent with a component under 1 keep their scale (#1249). Colour Image Trace keeps close dark tones apart (#1247). macOS: the Save sheet has a Format menu (#1235). The Hand and Zoom tools show drawn cursors on every platform (#1238). Czech: the remaining strings are translated, and Pathfinder's Add reads "Sjednotit" (#1226). MCP: a lost reply reports that the edit may have happened instead of replaying it (#1246); `select.key` checks its id and agents can read the key object (#1222). Tests: the command sweeps and import fuzz tests fail on a panic caught by the engine's guard (#1218), and the envelope export test ignores PDF dates and file IDs (#1220). Effect › Artistic › Film Grain (Grain, Highlight Area, Intensity; Photoshop-style filters 29/57) (#1282), and Craquelure, Mosaic Tiles and Stained Glass redraw 25–30% faster with identical pixels (#1265). Direct Selection: clicking a segment selects only that segment, and Delete removes just it (#1300); Shift-click deselects one anchor of a path selected whole (#1263). Pen + Alt converts anchors of paths inside a selected group or compound path (#1306). The Curvature tool shows circular point markers without direction handles (#1284). Snap to Point: pressing near an anchor drags by that anchor, with Smart Guides on or off (#1313). Transform Again repeats the options of the transform it repeats (#1303). Aligning anchors that are already aligned adds no undo step (#1276), and type commands that change nothing record none either (#1316). Simplify keeps the path selected with its new anchors, and its dialog previews and shows the anchor count (#1305). Adding a stroke colour to an unpainted zero-width stroke gives it a visible 1 pt width (#1256). The Eyedropper samples locked objects, template layers and art outside isolation mode (#1260), and shows a pipette cursor (#1288). Fonts named by their full name resolve to the right face (#1267), and Proportional Metrics brings the matching kerning (`apkn`, `vkrn`, `vapk`) (#1291). Artboards: Escape leaves Artboard editing (#1296), Document Setup's Edit Artboards switches to the Artboard tool (#1294), and the Artboard tool starts on the active artboard (#1309). New and imported documents use the Gridline every and Subdivisions preferences (#1314). Send to Current Layer refuses a hidden or locked current layer (#1301), and layer row commands check explicit ids (#1255). Links: Find in Folder… finds missing linked files in a folder and its subfolders and can copy them into the document's folder (#1287). Image Trace traces images over 64 megapixels scaled down instead of refusing them (#1315). DXF export marks closed curves as closed SPLINE entities (#1320). EPS import: closepath respects the path size limit (#1311). The interface is available in Hungarian (#1302), and more Czech labels are translated (#1259). Linux RPMs declare shared-library capabilities (#1290). CI pins every third-party action to a verified commit (#1321). Select menu commands skip hidden and locked art and stay inside the isolated group in isolation mode (#1325). Fill, stroke, gradient and Appearance panel commands that change nothing add no undo step (#1331). EPS import no longer hangs on shading functions fanned out through shared arrays (#1330), looped huge arcs, fine dashes and rectangle arrays (#1329), or very long dash patterns (#1332). Plug-in whole-number fields keep values past 2^53 exactly as typed (#1327). Large documents use far less memory: decoded images are shared and capped, undo history is bounded by memory, native files open in the background and save as a stream, and Data Recovery writes images once (#1245). Opacity mask commands (#1336), Simplify and Add Anchor Points (#1337) add no undo step when they change nothing. EPS files with thousands of tiling patterns, spot inks or clipped shadings open several times faster with the same result (#1341). A `.ai` or PDF saved from a CMYK document with transparency no longer opens blank in applications that read soft masks by luminosity (#1359, part of #1286). Gradient-filled shapes in a PDF or `.ai` open as one path with the gradient instead of a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on their outlines (#1351). A `.ai` saved with a bleed opens on its artboard with the bleed round it as the document's bleed, from its layers, and Crop To › Trim does the same for a PDF (#1349); a PDF saved with its editing data opens from it, with its layers, groups and art past the page, as a `.ai` does (#1345). Art moved into a hidden or locked layer (row drag, Merge Selected, Flatten Artwork, Collect in New Layer) or hidden by a data set is deselected (#1355), and hiding or locking a layer with a large selection deselects its objects in linear time (200,000 objects: 3.9 s to 24 ms) (#1353). Objects moved whole together with direct-selected anchors follow Preferences › Transform Pattern Tiles (#1354). Preferences › Appearance of Black › On Screen works: Display All Blacks as Rich Black shows 100K black as RGB black on the canvas (#1350). DXF: a closed control-point SPLINE opens as a closed path (#1318). Numeric fields: dragging over part of a value in an unfocused field selects that part instead of the whole value (#1339). Pathfinder Divide: an open line or curve across a filled shape cuts it into separate pieces (#1335); Unite, Minus Front, Minus Back, Intersect and Exclude results keep the source object's name, so exported SVG keeps its id (#1308). Object › Align follows the Align To choice (one object aligns to the artboard), and the choice is kept across restarts (#1347). Artboard tool: a click on an object creates an artboard fitted to it (#1252). Rulers: drag the ruler corner to move the zero point, double-click it to reset; the X/Y fields measure from it (#1250). Live Corners: with Direct Selection, a click on a corner widget selects that corner, so the next drag rounds it alone (#1239). A click with the Polar Grid tool opens a dialog for its size and divider counts, as the Rectangular Grid tool does (#1192). A `.ai` whose editing data holds an image on hidden lines is no longer misread (#1364, part of #1264). PDF export leaves out art placed beyond 1,000,000,000 pt instead of aborting debug and test builds (#1360). Affinity import: rectangles keep per-corner radii and straight (cut) corners (#1369, part of #666). Tools panel: the tool buttons are centred inside the panel border, in one and two columns (#1363). Spanish: 371 more interface strings translated (presets, shortcut editor, print and PDF options, Save for Web and more) (#1371). The Properties panel no longer widens and cuts off its labels when an Image Trace object is selected (#1374, part of #1358). Art drawn flush with an artboard (a background a rounding error outside it) moves, copies and scales with the artboard again (#1375, from #1295). A character no installed font had is looked for again after the fonts are rescanned, so installing a font fixes it without a restart (#1376, from #992). A PDF saved with its editing data and a bleed opens on its artboard with the bleed round it, as a `.ai` does (#1379, follow-up to #1349 and #1345). Dialogs opened from a menu focus their first field every time they open, not only the first time, so typing, Tab and Enter work (#1382, fixes #1367); a dialog whose first field is greyed out (Blend Options on Smooth Color, Layers Panel Options) gives the keyboard focus to that field once it is enabled (#1395). In a `.ai` opened from its editing data, a gradient with stops in the middle draws across its whole shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392) (follow-ups to #1264). `--control` without a valid port (or a bad `VECTORCRAFT_CONTROL_PORT`) stops the desktop app with an error instead of starting without a control server, and `--control=` works too (#1383). Documents with many symbol instances or inline graphics redraw faster and use less memory: the art placed for each instance is kept between frames (#1386). PDF and `.ai` import and placed PDFs keep overprint (`/OP`, `/op`), so overprinting spot colours still overprint after export (#1413, fixes #1388). A `.ai` whose PDF part draws only text opens from that part when its editing data can't be read, instead of being refused (#1414, fixes #1387). In a `.ai` opened from its editing data, a compound path takes the paint of its last path, so its gradient no longer comes in black, and paths grouped inside a compound path stay its paths (#1426, fixes #1410). With anchors selected with Direct Selection, the Scale, Rotate, Reflect and Shear tools, their dialogs and Move transform only those anchors (#1427, fixes #1408). The Move, Rotate, Scale, Reflect and Shear dialogs have a live Preview, and the arrow keys step their angles and percentages by 1 (Shift: 10) (#1428, fixes #1412). A stroke wider than its closed shape (a small ellipse or rectangle with a heavy stroke) paints solid on the canvas, as in exports, instead of showing a hole (#1409, fixes #1396). The bounding box hides while a corner radius is dragged with the Selection tool (#1402, fixes #1229). Pasting a picture works when the clipboard also holds a blank text item beside it (#1404). `document.inspect` reports a compound path's fill, stroke and weight and every node's blend mode when it isn't Normal (#1397, fixes #1389); `object.isolate` with an id that doesn't exist says there is no such object (#1415); the MCP guide covers Spacing Guides and four more preferences, all resources, and the symbol, brush, variable and Image Trace commands (#1418). PDF and `.ai` import keep a stroke opaque and unmasked when the fill under it was faded or masked by its group, and a `.ai` read as its PDF part keeps its RGB numbers (#1434). SVG export writes knockout groups of opaque art without masks (smaller files, no edge seams), and `vectorcraft-cli convert` takes `--decimals` (#1435). Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate and the copying transforms of thousands of objects take a fraction of a second instead of seconds (#1430, part of #1429), and an Alt-drag with the selection and transform tools copies the selection once per drag instead of on every move (#1464, part of #1429). An Affinity text frame too short for its first line (a 64 pt title in a 54 pt frame) is made taller on import, with a note, instead of showing nothing (#1449, fixes #1423). Fit Headline no longer pushes the tracking to its ceiling and loses glyphs when the frame holds one line (#1445, fixes #1444). Text frames, wrap shapes and type paths with coordinates beyond a billion points (from damaged files) hold no text instead of hanging the layout (#1451). Czech: 128 more strings translated (#1461). Plug-ins: a numeric parameter's default stays inside its declared range (#1463). Split Into Grid has the documented options: number, height or width, gutter and total for rows and columns, Add Guides and Preview; several selected paths become one grid painted as the topmost one (#1488, fixes #1462). Grayscale TIFFs with an alpha channel or other extra channels can be placed, relinked and opened, the alpha as the image's transparency (#1489, part of #1466). Selected text in numeric and dialog fields is drawn in white or black instead of blue on the blue highlight (#1490, part of #1465). The Pathfinder panel works on a group selected alone (its members are combined), and a greyed-out button says what it needs (#1493, for #1450). Transform Objects joins Transform Patterns in the Move, Rotate, Scale, Reflect and Shear dialogs and in Transform Each (off: only the pattern tiles transform), and Reflect takes an angle for its axis (#1494, fixes #1448 and #1460). A window larger than 8192 px (several monitors, a display-scale change) keeps its surface instead of closing the app (#1495, part of #1459). Commands run through MCP, the control channel and the CLI refuse a parameter key they don't take, naming it and the nearest accepted key (#1496, fixes #1442). A focused number field follows its value when a slider or preview changes it, so the next key no longer puts the old value back (#1497, fixes #1457). Effect › 3D and Materials: outlined words and other shapes of many small curves take Rotate, Extrude & Bevel and Inflate (curves are sampled by a tolerance; Rotate takes up to 65,536 outline points; #1481), Extrude & Bevel's Twist runs 0° to 360°, as the public panel reference gives it (#1524), and a twisted extrusion keeps its walls (from about 45° they were dropped; #1525). Text commands and the MCP `add_text` tool say 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, including one just added (#1487, fixes #1458). `graph.setData`'s CSV keeps each value exactly instead of rounding it to two decimals, so applying the returned CSV changes nothing (#1485). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible (#1505, fixes #1486). Sliders in Save for Web, the raster export options, Preferences and the opacity popup show their rail, filled up to the handle (#1506, fixes #1483). Direct Selection picks the anchor of the selected object where anchors of overlapping objects coincide, also under another object (#1509, fixes #1508). Print-size images (past 512 MB decoded, up to 2 GB) draw in the canvas and in raster exports and can be trimmed with Crop Image; an image whose side is past 65,535 px is shrunk to fit, a raster export says when an image could not be decoded, and Crop Image's trim leaves CMYK images alone (#1517). On Windows, `vectorcraft-cli perf` reports the cores busy and, with `--deep`, its working set, and warns on a busy machine as on macOS and Linux (#1502). French: 423 missing strings added and 188 entries reworded to the feature names French users know (#1511). Hungarian: one message uses the informal address like the rest of the interface (#1474). | | 2026-10-12 | Georgian interface (`ka`, ქართული): the whole catalog, plurals and messages, tested complete; Georgian letters come from an installed font (SF Georgian, Sylfaen, Noto Sans Georgian, DejaVu Sans) from the first frame; Type › Change Case › Title Case and Sentence case leave Georgian lower case instead of turning it into Mtavruli. | | 2026-10-11 | Effect › Brush Strokes: Accented Edges, Angled Strokes, Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes, Sumi-e (G2). Command parameters from agents and files checked before anything changes (paint, place, cuts, dashes, crop, asset ids, anchors, paths, distort; #984–#999); command dialogs keep whole numbers whole, so Create Object Mosaic takes the tiles typed (#1000); stepper arrows take Shift (×10) and Ctrl/Cmd (÷10) like the arrow keys (#991). Exports and Rasterize supersample Art Optimized edges, so shapes meeting edge to edge leave no seam (#983). Character and paragraph styles take leading, kerning, mojikumi and the other attributes left out at their defaults (#1001). Drawing, typing and pasting with no layer shown and unlocked is refused instead of adding art to a hidden or locked layer (#1002). MCP `add_text` gives type on or in a path the colour asked for (#1003). MCP `screenshot` of a connected app renders the artboard asked for (#1004). `vectorcraft-cli run` ends quietly when its reader closes early (#1005). Select › All on Active Artboard selects on the artboard made active, not always the first (#1006). Reverse Gradient keeps off-centre midpoints, mirrored (#1007). A polar grid with no radial dividers draws none (#1008). Use Precise Cursors also covers the Pen's join pointer (#1009). SVGs with one absolute and one unitless root side import at their size, unstretched (#1010). DXF US survey inches, yards and miles open at their size and name (#1011). A file placed into a document with no other links follows its first change even while the app sits idle (#1031). PDF import keeps the style a font name says when the file doesn't embed the font (#1023). Shift selects ruler guides and art together, and Delete removes both (#1022). Open filled paths are hit by their fill on every side, the rotate cursor bows around the corner it is at, the flip icons match their flips, the Color Picker previews on the selection, and Properties › Transform reaches Scale Corners and Scale Strokes & Effects (#1036). Offset Path and the other booleans finish on outlines where the sweep used to loop until memory ran out (linesweeper 0.5, #1028). Floating panel groups stack into sets that move together, collapse to their tabs and dock as extra dock columns that scroll (#1020). Ruler guides live on layers: listed in the Layers panel, shown, hidden, locked, duplicated, merged and deleted with their layer, and moved between layers (#1021). A `.ai` whose editing data uses global process colours (`Xk`/`XK`) or pattern fills keeps its sublayers: the colours come in as global swatches at their tint, the patterns as pattern swatches (#1025). A `.ai` in PostScript form opens through its layers, read from the program itself, also when it names the prolog defining its operators without including it, as Rhino and other CAD apps write it (#1027). A fill or stroke chosen while the Type tool has characters selected colours just those characters (#1063). Scaled type shows its scaled font size, leading, baseline shift and horizontal scale in the Character panel, and a size typed there is the size you get (#1034). Character panel menu › Proportional Metrics sets Japanese and Chinese full-width glyphs on the font's proportional widths in horizontal type (#966). Align, Distribute, Move, Arrange, Lock, Hide, Ungroup and other Object commands that would change nothing no longer record an undo step or mark the document changed (#1060). Spot colours defined in Lab open with their Lab values from `.ai` and PDF files, instead of as wrong RGB colours or their CMYK equivalents (#1032). Build scripts leave a generated source they wouldn't change untouched, so the next build doesn't compile most of the workspace again where file times lose their sub-second part (#1051). A fill colour recolours the gradient mesh point last clicked with the Mesh tool or Direct Selection, and a Mesh tool click on a mesh's point selects that mesh (#1052). The All Tools drawer stays two tools wide instead of filling a wide window (#1054). Text Wrap's Make, Release and Options refuse a list of object ids with a malformed or unknown id instead of skipping it (#1055). A freeform gradient line with a malformed point index is refused instead of being shortened to the indices that are valid (#1056). The Corners dialog (`ui.corners`) refuses a malformed object id or a listed anchor that isn't a corner instead of editing the selection or the other corners (#1057). New View refuses a centre that isn't exactly [x, y] and a rotation that isn't a number, instead of trimming the one and saving the other as 0° (#1058). The command sweeps try junk scale, spacing and artboard values too, which they had skipped since before those bugs were fixed (#1059). EPS and PostScript `arc` and `arcn` with huge angles no longer hang the import, and an arc whose angles are whole turns apart is empty, as the PostScript reference defines it (#1062). Align and Distribute Spacing keep the key object still also when it is inside a selected group or compound path (#1074). A `.ai` whose layers can't be read yet still opens with its artboards where they were (in a grid, say), not in a row (#1068). Layer Options (`ui.layerOptions`) refuses a malformed or unknown row id instead of skipping it or opening on the highlighted rows (#1077). Shaper scribbles given a list of object ids refuse a malformed or unknown id instead of skipping it and editing the shapes that remain (#1078). Delete Width Point (`stroke.widthPoint.remove`) refuses a list of indices with a malformed entry instead of deleting the points that remain, and no longer wraps a huge index round on the web (#1079). Preferences' checkboxes have an outline when the pointer isn't over them, in every interface brightness, as the app's other dialogs' checkboxes do (#1080). The last plain checkboxes (Properties panel snapping and Scale Strokes & Effects, Revolve, Save options, Export for Screens, Variables, plug-in forms) keep a visible box at rest in every theme too (#885). Setting or copying a width point with a malformed index is refused instead of adding a new point or wrapping a huge index round (follow-up to #1079). An Illustrator EPS opened through its layers keeps its own page size and the red outline of text stacked over a dark one, as 0.8.0 did (#1102). The macOS DMG is built so the app in it passes `codesign --verify --strict --deep`, and the release checks that it does (#1085). Swatch and graphic style libraries, Libraries panel files, presets and plug-ins dropped on the window open as File › Open opens them instead of being placed on the canvas (#1083). A key object needs another selected object outside it: a change that leaves one object selected lets the key go, and one selected object aligns to the artboard whatever Align To says (#1088). Align to Artboard aligns to the active artboard, and actions play their Align to Artboard, All on Active Artboard and Paste in Place, in Front and in Back steps on the artboard active when they play (#1105). Align refuses a call with neither direction, and Align, Distribute, Reflect and Shear refuse a direction, axis, target or bounds they don't take instead of falling back to a default (#1106). `object.setProps` deselects the objects it hides or locks, the key object included, as the Layers panel's eye and lock do (#1107). Align, Distribute and Distribute Spacing move pattern tiles with the art when General › Transform Pattern Tiles is on (#1108). Object › Lock › All Artwork Above and Object › Hide › All Artwork Above deselect the selected objects they lock or hide, the key object included (#1109). Save Swatch Library's `count` is the number of swatches the file holds: `.gpl` and `.ase` hold solid colors only, and CSS leaves freeform gradients out (#1110). In a rotated view (Rotate View), an artboard's name stays at its own top-left corner (#1095). Ctrl+Shift+L, C, R, J and F align or justify the paragraphs of the selected type, or those the Type tool's selection touches (#1111). On macOS, file dialogs are sheets on the document window, so resizing one no longer crashes the app; while one is open the menus, Quit and Close wait, and its answer goes to the document that asked (#867). Shape Builder merges regions that crossing lines cut along the lines' own edges, so a strip merged across a grid of lines is one outline with no seams left inside (#1081). Proportional Metrics also works in vertical type: upright glyphs take the font's proportional heights (`vpal`), and Line-end Punctuation Half Width takes nothing more off the punctuation it re-spaced (#1082). Plug-in whole-number parameters keep their exact value however large, and stay in the range the manifest gives (#1091). PDF and `.ai` import keeps type spaced glyph by glyph (character tightening, optical kerning) with each glyph in its place, giving each character its own tracking when the file's font is installed, and CJK punctuation closed up by its proportional width continues its line (#1101). Direct Selection: pressing an anchor of a path selected whole keeps all its anchors selected, so the drag moves them all; Alt-dragging by an anchor copies the whole path, held by that anchor, which snaps onto other anchors and onto the original the copy leaves behind; Alt pressed or released during the drag turns the copy on and off, as with the Selection tool, whose copies snap to their original too, and the undo step is named Copy or Move for what the drag did (#1104). The toolbar's Fill/Stroke proxy and Color, Gradient and None buttons grow in two columns, where the three drawing modes sit side by side (#1129). An image copied in a browser that puts its `` markup on the clipboard as text pastes as the picture, not the markup (#1089). `file.place` of an SVG with `crop: "crop"` frames and clips it by its viewBox, so art drawn on a shared canvas keeps its place and scale (#788). While a star is dragged, Ctrl/Cmd keeps its inner radius as the outer one grows and Alt keeps its shoulders straight (#812). Edit Toolbar opens the All Tools drawer beside the toolbar, dims the tools already in it, and adds, removes and moves tools by drag and drop while it is open (#1018). The Selection tool's arrow is black and Direct Selection's white in every theme, as users know them: in the dark themes they looked swapped. The font menu keeps its highlight on the same font when the list changes under it (a family's styles listed above it, fonts that finish loading, a favourite unstarred), and ends the live preview when that font leaves the list (#1116). The Windows installer has a Shortcuts page with a ticked "Create a desktop shortcut" box, and a silent install adds the shortcut unless `INSTALLDESKTOPSHORTCUT=""` is passed (#1128). Image Trace's Noise merges specks until none under its size is left beside another colour, so a higher Noise never gives more paths (#1130). `cargo clippy -D warnings` passes for the wasm32 web build (#1132). Gradient stops with opacity blend colour and opacity apart on the canvas, as Illustrator and the PDF and SVG exports do: a transparent stop's colour still tints the fade (#1142). An SVG mask whose art is all hidden imports as an empty opacity mask, so its object stays hidden as browsers draw it (#1143). Shift-click with the Artboard tool, or in the Artboards panel, selects several artboards, which then move, duplicate (Alt-drag) and delete together (#1139). A shape far beyond any page (from a malformed file) is left undrawn instead of making the renderer abort the app. Live Corners round corners where curved segments meet too, trimming each curve to what the cut leaves of it (#1144). Effect › Distort & Transform › Zig Zag's dialog has sliders for Size and Ridges per segment, and Relative / Absolute and Smooth / Corner as radio buttons (#1133). Object › Path › Offset Path opens on the offset, joins and miter limit it was last applied with (#1152). A marquee selects only the objects whose paths it touches: one drawn over a background, in Preview or Outline, no longer selects the background too (#1103). On Linux, Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland on a Wayland session, where files dropped from a file manager arrive (#1151). A selected gradient mesh shows its mesh lines and points with the Selection and Direct Selection tools too, not only with the Mesh tool (#1111). A blend's spine bends: the Anchor Point tool drags any of its segments into a curve, straight ones too, and Direct Selection reshapes its curved segments (`object.blend.spine.reshapeSegment`, #1111). Alt-click on a hidden layer's eye shows that layer as it hides the others, and on a locked layer's lock unlocks it as it locks the others: the layer clicked is the one left in view (#1158). Object › Compound Path › Release splits a path of several subpaths (an SVG `d` with several `M`s, a path drawn in one go over MCP) into one path per subpath, with its paint and stacking order, as it does a compound path (#1163). MCP `render_preview` takes an `artboard` index, so an agent can look at every page of a multi-artboard document (#1163). The MCP drawing tools say that omitted paint follows the new-art appearance (a white fill and 1 pt black stroke at first), and `export` says which formats take `outlineText` (#1148). The desktop app refuses a malformed `--automation-read-root` / `--automation-write-root` (no folder, an empty one, another option or the flag twice) before it starts, instead of dropping the root its environment variable set and leaving the control channel unconfined (#1157). PDF export warns, once per object, when the 64 million pixel cap renders its raster effects below the document's raster effects resolution, with the requested and the achieved ppi (#1147). MCP `command_batch` with `atomic: true` makes the whole batch one undo step, named by `label` (`edit.undoGroup.begin`/`end`, #1163). `file.list {path}` lists a folder's files and folders for agents, held to the automation read root (#1163). Thai typed in a font without Thai glyphs is set in an installed font made for Thai (Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai…) instead of whichever face with Thai glyphs loaded first, and Lao, Khmer and Myanmar likewise. With the Type tool, the Left and Right arrows and Delete step over whole clusters (a Thai consonant with its vowel and tone marks, a letter with a combining accent, an emoji sequence), so the caret never lands inside one; Backspace still takes back one character at a time, a mistyped tone mark say. Thai, Lao, Khmer and Myanmar area type breaks its lines between words, which those scripts don't separate with spaces, instead of running on to the next space; the words come from ICU4X's line segmenter (its dictionaries on the desktop, its smaller LSTM models on the web). The font menu's script filter has Thai beside Japanese and Latin: the families whose character map has Thai. With craft-fonts' Noto Sans Thai, Thai is set in it where no Thai font is installed, and the web build fetches it before the app starts, so Thai no longer shows as empty boxes there. With the Type tool, Ctrl/Alt+arrows and double-click take Thai, Lao, Khmer and Myanmar text word by word (ภาษา, ไทย…) instead of a whole run without spaces, and a word's vowel and tone marks (and combining accents) stay part of it. Releases embed the current craft-fonts (Noto Sans Thai, Noto Sans Arabic and Noto Sans CJK SC beside the Japanese fonts), as the other craft apps' releases do. Object › Compound Path › Make cuts holes where the paths in front overlap the backmost one, also when they were drawn running the same way (#1197). On Windows, Direct3D 12 shaders compile with FXC, part of Windows, so a dxcompiler.dll another program left on the search path without its dxil.dll no longer loses the graphics device at start-up and drops the app to OpenGL (#1194). With anchor points selected by Direct Selection, the Align buttons align those points (to their own bounds or the artboard) instead of moving the whole path (#1180). With Smart Guides, an object grabbed by an anchor and dropped near another object's anchor lands exactly on it, instead of its bounds lining up a fraction of a point beside it (#955). .ai import: a copied area type or type-on-a-path object now sits where its own art puts it, not on top of the original (#1208). EPS/.ai import: a font is found by its exact PostScript name before the name is split, so families with hyphens keep their name (#1207). EPS/.ai import: type from the text document keeps its line spacing across paragraphs instead of applying the paragraph spacing twice (#1206). Brazilian Portuguese translates the remaining UI labels and engine messages (#1205). Czech joins the complete languages: panels, dialogs, plurals and status and error messages (#1189). Type: Digits (Character panel menu, with the Middle Eastern options) draws every digit in the Default, Arabic, Hindi or Farsi numeral system (#1201). Linux: under Wayland, Automatic draws on the GPU the compositor says it draws with, so a hybrid laptop whose compositor runs on the discrete GPU no longer opens an empty window (#1200). Large documents: editing a big selection takes time linear in the document (a 25,000-path nudge 3.5 s → 48 ms), live geometry effects are kept across frames, Pathfinder Trim, Merge, Crop and Outline are 9–20× faster with identical output, and undo history holds 41% less (#1173). | -| 2026-10-10 | Initial live Revolve (Effect › 3D and Materials, #846, #605), in its own `three-d` crate. Progress docs re-measured and restructured to the craftrules standard (this page, `docs/target-app-parity.md`, `gaps.md`, `ui-parity.md`, the format, hardware, localization, effects and type checklists). Same day: v0.8.0; Effect › Distort, Pixelate and Texture filters (13); German interface; Variables (data merge); Graph Type value axes and tick marks; restart when the first frame never reaches the screen (#964) | +| 2026-10-10 | Initial live Revolve (Effect › 3D and Materials, #846, #605), in its own `three-d` crate. Progress docs re-measured and restructured (this page, `docs/target-app-parity.md`, `gaps.md`, `ui-parity.md`, the format, hardware, localization, effects and type checklists). Same day: v0.8.0; Effect › Distort, Pixelate and Texture filters (13); German interface; Variables (data merge); Graph Type value axes and tick marks; restart when the first frame never reaches the screen (#964) | | 2026-10-09 | Radial Blur, Smart Blur, Unsharp Mask (gap 2 begins); 340 commits, the busiest day | | 2026-10-08 | v0.5.0–v0.7.0; community contributions: Pen and shape-tool modifiers, Layers, Artboards, Japanese composition, Hebrew/Arabic type, interface languages, saved selections | | 2026-10-07 | v0.4.0; issue fixes; Layers panel rework | @@ -192,12 +206,24 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | 2026-10-01 | Renamed from DrawCraft to VectorCraft | | 2026-09-30 | Repository history begins | -The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/roadmap.md#progress-log-before-the-progress-docs-standard). +The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap.md#earlier-progress-log). ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. | +| 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. | +| 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. | +| 2026-10-29 | minor | Progress log row for the Linux Flatpak clipboard's core Wayland protocol text fallback; headline numbers unchanged. | +| 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. | @@ -217,7 +243,7 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro | 2026-10-13 | minor | Bounded synthetic control input (#1709): counts and queued events validated before mutation; control-channel bursts yield between frames. Scores and hours unchanged. | | 2026-10-14 | minor | Progress log row for the merges of 2026-10-14 (#1641–#1808 as listed there) and Image Trace's #1647 and #1657; the 2026-10-13 row now says that a guide's position in the Transform panel (#1659) is not established by the documentation found and is kept as a convenience pending the owner's decision; headline numbers unchanged. | | 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. | -| 2026-10-10 | minor | Method aligned with the standard, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away | +| 2026-10-10 | minor | Method changed, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away | | 2026-10-10 | minor | Added the essentials-user readiness score (~75%) | | 2026-10-10 | minor | Ready for real work re-examined against the issue tracker and user feedback: 50% → 55% (full), 65% mainstream added; see target-app-parity.md | | 2026-10-10 | minor | Applied the core-workflow gate (docs/roadmap.md › Alpha gate): passes, stage stays alpha | diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index cb9183315f..8f39e3b58d 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -34,8 +34,9 @@ winsafe = { version = "0.0.29", default-features = false, features = ["kernel", # DirectWrite's system font collection and GDI's font list (the desktop app's src/system_fonts.rs, # shared): fonts that font services such as Adobe Fonts load in place (#579, #1258). MIT OR -# Apache-2.0. -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi"] } +# Apache-2.0. Win32_System_Threading has `GetProcessAffinityMask`, which the desktop app's +# src/windows_cores.rs, shared, uses to count the cores the process may run on. +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading"] } # CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font # managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index bba1976c1d..b7334586ca 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -49,6 +49,10 @@ mod prefs_dir; #[cfg(windows)] #[path = "../../vectorcraft/src/system_fonts.rs"] mod system_fonts; +/// The desktop app's affinity-mask reader, shared: renders start workers only for usable cores. +#[cfg(windows)] +#[path = "../../vectorcraft/src/windows_cores.rs"] +mod windows_cores; use serde_json::{Value, json}; use vectorcraft_engine::file_access::{self, AutomationRoots}; @@ -161,6 +165,9 @@ fn help() -> Result<(), String> { } fn main() -> ExitCode { + // Before the first render: the cores the process may run on. + #[cfg(windows)] + windows_cores::install(); // Before any font lookup: the fonts font services load (#579). #[cfg(windows)] system_fonts::install(); diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index 8fe3d23b74..ac3a9cf3ae 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -116,7 +116,7 @@ fn edit_drags(n: usize) -> Result<(f64, f64), String> { let view = vectorcraft_engine::ViewInfo { zoom: 8.0, ..Default::default() }; let err = |e: vectorcraft_engine::EngineError| e.to_string(); let mut drag = |down: Point| -> Result { - let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), pressure: 1.0 }; + let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), backquote: false, pressure: 1.0 }; s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 400]]})).map_err(err)?; s.select_tool("directSelection", view).map_err(err)?; let undo = s.doc().map_err(err)?.history.undo.len(); @@ -215,7 +215,7 @@ fn deep(n: usize) -> Result<(), String> { let first = s.doc().map_err(err)?.selection.objects.first().copied(); let at = first.and_then(|id| s.doc().ok()?.doc.node(id)?.geometric_bounds()).map(|b| b.center()); if let Some(down) = at { - let ev = |kind, dx: f64| PointerEvent { kind, pos: down + Vec2::new(dx, 0.0), mods: Mods::default(), pressure: 1.0 }; + let ev = |kind, dx: f64| PointerEvent { kind, pos: down + Vec2::new(dx, 0.0), mods: Mods::default(), backquote: false, pressure: 1.0 }; s.select_tool("selection", view).map_err(err)?; s.pointer(&ev(PointerKind::Down, 0.0), view).map_err(err)?; let mut dx = 0.0; diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 3173d3bc97..47d26eb7b6 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -54,7 +54,12 @@ pollster = "1" # Win32_UI_WindowsAndMessaging has `MSG` and `WM_POINTERDOWN`, which src/windows_stylus.rs uses to # read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has # `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down. -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the +# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which +# src/caps_lock.rs uses to read whether Caps Lock is on. +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } +# The renderer's worker count follows those cores (src/windows_cores.rs). +vectorcraft-render = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] # The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK @@ -86,12 +91,16 @@ pollster = "1" winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] } # A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a # second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build -# through winit with the `xinput` feature. -x11rb = { version = "0.13", default-features = false, features = ["xinput"] } +# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs). +x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] } # 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" +# Copy and Paste of text through the compositor's core data-device protocol on the window's +# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak +# on a Wayland session). MIT, already in the build through egui-winit. +smithay-clipboard = "0.7" wayland-protocols = { version = "0.32", features = ["client", "unstable"] } # The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in # wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index 2847004b34..423fb53fc7 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,6 +1,8 @@ #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] use super::gpu; -use super::prefs::save_prefs; +use super::prefs::{save_prefs, save_prefs_soon}; +#[cfg(not(target_os = "macos"))] +use super::single_instance; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; use super::{App, VectorcraftApp, file_access, window}; @@ -66,11 +68,17 @@ impl eframe::App for App { // macOS converts the frame from sRGB to the display's profile (#2249). #[cfg(all(target_os = "macos", feature = "wgpu"))] super::mac_color_space::tag(ui); + if let Some(on) = self.host_caps_lock.read_transition() { + self.app.set_caps_lock(on); + } file_access::unconfined(|| self.app.ui(ui)); // Preferences are written when confirmed, not only at exit: a session ended any other way // (the system shutting down, the process ended or crashing) used to lose them (#1747). if self.app.take_prefs_changed() { file_access::unconfined(|| save_prefs(&self.app)); + } else { + // The workspace, panels and other UI settings change without the dialog (#4625). + file_access::unconfined(|| save_prefs_soon(&self.app)); } // Not while a file dialog's sheet has the keyboard: its name field's composition would go. #[cfg(target_os = "macos")] @@ -102,11 +110,13 @@ impl App { vectorcraft_ui_egui::background::wait_all(&mut self.app); return; } - // Files from the Finder and the Dock wait while a file dialog is open: what asked for it runs - // again on its document when it answers. - #[cfg(target_os = "macos")] + // Files from the Finder and the Dock (macOS) or from later launches (#4892) wait while a file + // dialog is open: what asked for it runs again on its document when it answers. if !self.app.file_dialog_open() { + #[cfg(target_os = "macos")] let files = open_documents::take(); + #[cfg(not(target_os = "macos"))] + let files = single_instance::take(); if !files.is_empty() { bring_window_forward(ctx); } @@ -144,15 +154,15 @@ fn end_before_teardown(frames: u64) { } } -/// Show the window when files are opened from the Finder or the Dock: a minimized window comes back -/// out of the Dock and the app takes focus, as a document-based Mac app does (#3769). -#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +/// Show the window when files are opened from the Finder or the Dock, or handed over by a later +/// launch (#4892): a minimized window comes back and the app takes focus, as a document-based app +/// does (#3769). pub(crate) fn bring_window_forward(ctx: &egui::Context) { ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); ctx.send_viewport_cmd(egui::ViewportCommand::Focus); } -/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that +/// Open files handed to the app (command line, macOS Finder and Dock, later launches) as documents. A file that /// can't be opened is reported to the user and on stderr; the others still open. pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec) { for f in files { diff --git a/apps/vectorcraft/src/caps_lock.rs b/apps/vectorcraft/src/caps_lock.rs new file mode 100644 index 0000000000..231a37e037 --- /dev/null +++ b/apps/vectorcraft/src/caps_lock.rs @@ -0,0 +1,216 @@ +//! Read the host's Caps Lock state, which gives the drawing tools the precise crosshair while it is on. + +/// Only host transitions replace a value set by a script through `view.capsLock`. +#[derive(Default)] +pub struct HostCapsLock { + previous: Option, + #[cfg(target_os = "linux")] + x11: Option, +} + +#[cfg(target_os = "linux")] +struct X11CapsLock { + connection: x11rb::rust_connection::RustConnection, + locked: bool, + initial_sequence: u16, +} + +impl HostCapsLock { + pub fn new(window: Option<&winit::window::Window>) -> Self { + #[cfg(target_os = "linux")] + let x11 = window.and_then(x11_connection); + #[cfg(not(target_os = "linux"))] + let _ = window; + Self { + previous: None, + #[cfg(target_os = "linux")] + x11, + } + } + + pub fn read_transition(&mut self) -> Option { + #[cfg(target_os = "linux")] + let current = match self.x11.as_mut() { + Some(state) => match state.poll() { + Some(locked) => Some(locked), + None => { + self.x11 = None; + None + } + }, + None => { + // Native Wayland does not expose the seat's XKB lock bit through winit or egui. + None + } + }; + #[cfg(any(target_os = "macos", windows))] + let current = Some(read()); + // This platform has no lock-state reader. + #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] + let current = None; + self.transition(current) + } + + fn transition(&mut self, reading: Option) -> Option { + reading.and_then(|current| self.observe(current)) + } + + fn observe(&mut self, current: bool) -> Option { + if self.previous.replace(current) == Some(current) { None } else { Some(current) } + } +} + +#[cfg(target_os = "linux")] +fn x11_connection(window: &winit::window::Window) -> Option { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + use x11rb::protocol::xkb; + if !matches!(window.window_handle().ok()?.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) { + return None; + } + let (connection, _) = x11rb::connect(None).ok()?; + let supported = x11rb::protocol::xkb::use_extension(&connection, 1, 0).ok()?.reply().ok()?.supported; + if !supported { + return None; + } + // Subscribe before the initial read so changes during setup remain queued. + xkb::select_events( + &connection, + xkb::ID::USE_CORE_KBD.into(), + xkb::EventType::default(), + xkb::EventType::default(), + xkb::MapPart::default(), + xkb::MapPart::default(), + &xkb::SelectEventsAux { + state_notify: Some(xkb::SelectEventsAuxStateNotify { + affect_state: xkb::StatePart::MODIFIER_LOCK, + state_details: xkb::StatePart::MODIFIER_LOCK, + }), + ..Default::default() + }, + ) + .ok()? + .check() + .ok()?; + let (locked, initial_sequence) = read_x11(&connection)?; + Some(X11CapsLock { connection, locked, initial_sequence }) +} + +#[cfg(target_os = "linux")] +impl X11CapsLock { + fn poll(&mut self) -> Option { + use x11rb::connection::Connection as _; + use x11rb::protocol::Event; + while let Some(event) = self.connection.poll_for_event().ok()? { + if let Event::XkbStateNotify(state) = event + // Events queued before the initial GetState reply must not replace that newer snapshot. + && state.sequence.wrapping_sub(self.initial_sequence) < 0x8000 + { + self.locked = lock_modifier_is_set(state.locked_mods); + } + } + Some(self.locked) + } +} + +#[cfg(target_os = "linux")] +fn read_x11(connection: &x11rb::rust_connection::RustConnection) -> Option<(bool, u16)> { + use x11rb::protocol::xkb; + let state = xkb::get_state(connection, xkb::ID::USE_CORE_KBD.into()).ok()?.reply().ok()?; + Some((lock_modifier_is_set(state.locked_mods), state.sequence)) +} + +#[cfg(target_os = "linux")] +fn lock_modifier_is_set(modifiers: x11rb::protocol::xproto::ModMask) -> bool { + use x11rb::protocol::xproto::ModMask; + u16::from(modifiers) & u16::from(ModMask::LOCK) != 0 +} + +#[cfg(target_os = "macos")] +const MAC_CAPS_LOCK: usize = 1 << 16; + +#[cfg(target_os = "macos")] +fn mac_flags_have_caps_lock(flags: usize) -> bool { + flags & MAC_CAPS_LOCK != 0 +} + +#[cfg(target_os = "macos")] +pub fn read() -> bool { + mac_flags_have_caps_lock(objc2_app_kit::NSEvent::modifierFlags_class().bits()) +} + +#[cfg(windows)] +fn windows_state_has_caps_lock(state: i16) -> bool { + state & 1 != 0 +} + +#[cfg(windows)] +#[allow(unsafe_code)] +pub fn read() -> bool { + // GetKeyState reports the toggle bit for the calling UI thread's keyboard state. + use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_CAPITAL}; + // SAFETY: `GetKeyState` takes a virtual-key code by value and reads no caller memory. + windows_state_has_caps_lock(unsafe { GetKeyState(i32::from(VK_CAPITAL.0)) }) +} + +// Querying XWayland for a native Wayland window would read a different keyboard. + +#[cfg(test)] +mod tests { + #[test] + fn no_host_reader_preserves_scripted_value_and_next_reading_transitions() { + let mut host = super::HostCapsLock::default(); + let mut session = vectorcraft_engine::Session::new(); + session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); + if let Some(on) = host.transition(None) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(session.caps_lock); + assert_eq!(host.transition(Some(false)), Some(false)); + } + + #[cfg(target_os = "linux")] + #[test] + fn no_x11_reader_has_no_transition() { + assert_eq!(super::HostCapsLock::default().read_transition(), None); + } + + #[test] + fn scripted_value_survives_unchanged_host_until_transition() { + let mut host = super::HostCapsLock::default(); + let mut session = vectorcraft_engine::Session::new(); + if let Some(on) = host.observe(false) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); + if let Some(on) = host.observe(false) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(session.caps_lock); + session.execute("view.capsLock", &serde_json::json!({"on": false})).unwrap(); + if let Some(on) = host.observe(true) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(session.caps_lock); + if let Some(on) = host.observe(false) { + session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); + } + assert!(!session.caps_lock); + } + + #[cfg(target_os = "macos")] + #[test] + fn mac_modifier_flags_map_caps_lock() { + assert!(!super::mac_flags_have_caps_lock(0)); + assert!(!super::mac_flags_have_caps_lock(1 << 17)); + assert!(super::mac_flags_have_caps_lock(1 << 16)); + assert!(super::mac_flags_have_caps_lock((1 << 16) | (1 << 17))); + } + + #[cfg(windows)] + #[test] + fn windows_key_state_maps_toggle_bit() { + assert!(!super::windows_state_has_caps_lock(0)); + assert!(!super::windows_state_has_caps_lock(i16::MIN)); + assert!(super::windows_state_has_caps_lock(1)); + } +} diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index ef3832f1e2..08bb6aa8a9 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -9,7 +9,10 @@ //! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on //! Linux arboard reads no other formats). On Wayland, arboard's data-control //! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps -//! copied), falling back to X11 where the compositor lacks the protocol. +//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no +//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection, +//! text only. A clipboard that can't be opened is tried again after a wait that grows to a +//! minute, not each time Paste asks. //! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS, //! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). @@ -19,12 +22,16 @@ use std::path::PathBuf; use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour}; use vectorcraft_ui_egui::SystemClipboard; -/// This platform's system clipboard. -pub fn system_clipboard() -> Box { +/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text where +/// arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11). +pub fn system_clipboard(window: Option>) -> Box { #[cfg(windows)] - let cb = Box::::default(); + let cb = { + let _ = window; + Box::::default() + }; #[cfg(not(windows))] - let cb = Box::::default(); + let cb = Box::new(portable::Clipboard::new(window)); cb } @@ -306,10 +313,14 @@ mod win { } } -/// arboard: one format at a time. Built everywhere so it is checked everywhere. +/// arboard, or on a Wayland compositor without its data-control protocol the core protocol's text +/// clipboard: one format at a time. Built everywhere so it is checked everywhere. #[cfg_attr(windows, allow(dead_code))] mod portable { use std::borrow::Cow; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; use super::{BITMAP, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of}; @@ -319,19 +330,216 @@ mod portable { Image(usize, usize), } - #[derive(Default)] + /// An open clipboard connection. + enum Backend { + Arboard(arboard::Clipboard), + /// The compositor's core data-device protocol on the window's connection (text only). + #[cfg(target_os = "linux")] + Wayland(super::wayland::TextClipboard), + } + + /// What a write of a picture says where the clipboard carries text only. + #[cfg(target_os = "linux")] + const TEXT_ONLY: &str = "this clipboard carries text only"; + + impl Backend { + /// arboard (Wayland data-control, else X11), else the core protocol on `window`'s + /// Wayland connection. Err: why each failed. + fn open(window: Option<&Arc>) -> Result { + first_open( + || arboard::Clipboard::new().map(Self::Arboard).map_err(|e| e.to_string()), + || { + #[cfg(target_os = "linux")] + return window.and_then(|w| super::wayland::TextClipboard::new(w.clone())).map(Self::Wayland).ok_or("not a Wayland window"); + #[cfg(not(target_os = "linux"))] + { + let _ = window; + Err("not on Linux") + } + }, + ) + } + + fn name(&self) -> &'static str { + match self { + Self::Arboard(_) => "arboard", + #[cfg(target_os = "linux")] + Self::Wayland(_) => "the Wayland core protocol (text only)", + } + } + + fn get_text(&mut self) -> Result { + match self { + Self::Arboard(cb) => cb.get_text().map_err(|e| e.to_string()), + #[cfg(target_os = "linux")] + Self::Wayland(cb) => cb.get_text(), + } + } + + fn set_text(&mut self, text: &str) -> Result<(), String> { + match self { + Self::Arboard(cb) => cb.set_text(text).map_err(|e| e.to_string()), + #[cfg(target_os = "linux")] + Self::Wayland(cb) => { + cb.set_text(text); + Ok(()) + } + } + } + + fn get_image(&mut self) -> Result, String> { + match self { + Self::Arboard(cb) => cb.get_image().map_err(|e| e.to_string()), + #[cfg(target_os = "linux")] + Self::Wayland(_) => Err(TEXT_ONLY.into()), + } + } + + fn set_image(&mut self, img: arboard::ImageData<'_>) -> Result<(), String> { + match self { + Self::Arboard(cb) => cb.set_image(img).map_err(|e| e.to_string()), + #[cfg(target_os = "linux")] + Self::Wayland(_) => Err(TEXT_ONLY.into()), + } + } + + fn clear(&mut self) -> Result<(), String> { + match self { + Self::Arboard(cb) => cb.clear().map_err(|e| e.to_string()), + #[cfg(target_os = "linux")] + Self::Wayland(cb) => { + cb.set_text(""); + Ok(()) + } + } + } + + /// Files copied in a file manager (none where the backend can't read a file list). + fn file_list(&mut self) -> Vec { + match self { + Self::Arboard(cb) => cb.get().file_list().unwrap_or_default(), + #[cfg(target_os = "linux")] + Self::Wayland(_) => vec![], + } + } + } + + /// The first of `arboard` and `wayland` that opens, tried in that order. Err: why each failed. + fn first_open(arboard: impl FnOnce() -> Result, wayland: impl FnOnce() -> Result) -> Result { + let arboard = match arboard() { + Ok(cb) => return Ok(cb), + Err(e) => e, + }; + wayland().map_err(|wayland| format!("arboard: {arboard}; Wayland core protocol: {wayland}")) + } + + /// Who asks for the clipboard: the background paste check waits out the whole wait after a + /// failure, a Copy or Paste of the user's [`USER_RETRY`] at most. + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + pub(super) enum Asker { + Probe, + User, + } + + /// The wait after the first failure to open the clipboard; it doubles with each failed retry. + const FIRST_WAIT: Duration = Duration::from_secs(1); + /// The longest wait between retries. + const MAX_WAIT: Duration = Duration::from_secs(60); + /// A Copy or Paste of the user's retries at most this often. + const USER_RETRY: Duration = Duration::from_secs(1); + + /// Whether "unavailable" has been logged and not yet answered by "available again": the + /// clipboard and its background check hold a handle each, and their failures are one outage. + static UNAVAILABLE_LOGGED: AtomicBool = AtomicBool::new(false); + + /// A failure to open, and when to try again. + struct Failed { + at: Instant, + wait: Duration, + } + + /// A handle opened on first use and kept, or after a failure opened again only once its wait is + /// over: where neither backend opens, asking a few times a second must not reconnect each time. + pub(super) struct Reopen { + handle: Option, + failed: Option, + /// The outage flag shared with the other handles ([`UNAVAILABLE_LOGGED`]). + logged: &'static AtomicBool, + } + + impl Reopen { + pub(super) fn new(logged: &'static AtomicBool) -> Self { + Self { handle: None, failed: None, logged } + } + + /// The open handle, opened with `open` when there is none and `asker` may try at `now`. + /// `name` names an opened handle in the log. + pub(super) fn get( + &mut self, + asker: Asker, + now: Instant, + open: impl FnOnce() -> Result, + name: impl Fn(&B) -> &'static str, + ) -> Option<&mut B> { + if self.handle.is_none() { + if let Some(f) = &self.failed { + let wait = match asker { + Asker::Probe => f.wait, + Asker::User => f.wait.min(USER_RETRY), + }; + if now.saturating_duration_since(f.at) < wait { + return None; + } + } + match open() { + Ok(handle) => { + if self.logged.swap(false, Ordering::Relaxed) { + log::info!("the system clipboard is available again, through {}", name(&handle)); + } else { + log::debug!("system clipboard opened through {}", name(&handle)); + } + self.failed = None; + self.handle = Some(handle); + } + Err(why) => { + let wait = match &self.failed { + Some(f) => (f.wait * 2).min(MAX_WAIT), + None => FIRST_WAIT, + }; + if self.logged.swap(true, Ordering::Relaxed) { + log::debug!("the system clipboard is still unavailable ({why}); next try in {wait:?}"); + } else { + log::warn!("the system clipboard is unavailable ({why}): Copy and Paste stay inside VectorCraft"); + } + self.failed = Some(Failed { at: now, wait }); + } + } + } + self.handle.as_mut() + } + + /// The handle if one is open, without trying to open one. + pub(super) fn opened(&mut self) -> Option<&mut B> { + self.handle.as_mut() + } + } + pub struct Clipboard { /// Kept open: on Linux the copied data lives as long as the handle does. - cb: Option, + cb: Reopen, + /// The app window, for the Wayland core protocol (on its connection). + window: Option>, ours: Option, } impl Clipboard { - fn cb(&mut self) -> Result<&mut arboard::Clipboard, String> { - if self.cb.is_none() { - self.cb = Some(arboard::Clipboard::new().map_err(|e| e.to_string())?); - } - self.cb.as_mut().ok_or_else(|| "no system clipboard".to_string()) + pub fn new(window: Option>) -> Self { + Self { cb: Reopen::new(&UNAVAILABLE_LOGGED), window, ours: None } + } + + fn cb(&mut self, asker: Asker) -> Result<&mut Backend, String> { + let window = self.window.as_ref(); + self.cb.get(asker, Instant::now(), || Backend::open(window), Backend::name).ok_or_else(|| "no system clipboard".to_string()) } } @@ -342,19 +550,19 @@ mod portable { Some(_) => None, None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)), }; - let cb = self.cb()?; + let cb = self.cb(Asker::User)?; let ours = match (text, image) { (Some(t), _) => { - cb.set_text(t.as_str()).map_err(|e| e.to_string())?; + cb.set_text(t.as_str())?; Some(Ours::Text(t)) } (None, Some(img)) => { let (width, height) = (img.width() as usize, img.height() as usize); - cb.set_image(arboard::ImageData { width, height, bytes: Cow::Owned(img.into_raw()) }).map_err(|e| e.to_string())?; + cb.set_image(arboard::ImageData { width, height, bytes: Cow::Owned(img.into_raw()) })?; Some(Ours::Image(width, height)) } (None, None) => { - cb.clear().map_err(|e| e.to_string())?; + cb.clear()?; None } }; @@ -363,7 +571,7 @@ mod portable { } fn holds_ours(&mut self) -> bool { - let Some(cb) = self.cb.as_mut() else { return false }; + let Some(cb) = self.cb.opened() else { return false }; match &self.ours { Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t), Some(Ours::Image(w, h)) => cb.get_image().is_ok_and(|now| (now.width, now.height) == (*w, *h)), @@ -372,8 +580,8 @@ mod portable { } fn read(&mut self, mimes: &[&'static str]) -> Option { - let cb = self.cb().ok()?; - if let Some(f) = cb.get().file_list().ok().and_then(|paths| copied_file(paths, mimes)) { + let cb = self.cb(Asker::User).ok()?; + if let Some(f) = copied_file(cb.file_list(), mimes) { return Some(f); } mimes.iter().find_map(|m| { @@ -402,7 +610,309 @@ mod portable { if super::mac::has(mimes) { return true; } - mimes.contains(&TEXT) && self.cb().is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty())) + mimes.contains(&TEXT) && self.cb(Asker::Probe).is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty())) + } + } + + #[cfg(test)] + mod tests { + use std::cell::Cell; + + use super::*; + + /// A clock that starts now and moves only when told. + struct Clock(Cell); + + impl Clock { + fn new() -> Self { + Self(Cell::new(Instant::now())) + } + fn now(&self) -> Instant { + self.0.get() + } + fn advance(&self, by: Duration) { + self.0.set(self.0.get() + by); + } + } + + fn fail() -> Result { + Err("no compositor".into()) + } + + fn name(_: &u8) -> &'static str { + "fake" + } + + #[test] + fn the_paste_check_retries_with_a_growing_wait() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let (clock, attempts) = (Clock::new(), Cell::new(0)); + let mut cb = Reopen::new(&LOGGED); + // Every 250 ms for a minute, as `clipboard_probe` asks. + for _ in 0..240 { + let open = || { + attempts.set(attempts.get() + 1); + fail() + }; + assert!(cb.get(Asker::Probe, clock.now(), open, name).is_none()); + clock.advance(Duration::from_millis(250)); + } + // 0, 1, 3, 7, 15 and 31 s: not one connection a check. + assert_eq!(attempts.get(), 6); + assert!(LOGGED.load(Ordering::Relaxed), "the outage is logged"); + } + + #[test] + fn the_wait_stops_growing_at_a_minute() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let (clock, attempts) = (Clock::new(), Cell::new(0)); + let mut cb = Reopen::new(&LOGGED); + for _ in 0..(20 * 60) { + let open = || { + attempts.set(attempts.get() + 1); + fail() + }; + let _ = cb.get(Asker::Probe, clock.now(), open, name); + clock.advance(Duration::from_secs(1)); + } + // 0, 1, 3, 7, 15, 31, 63 s, then a minute apart until 20 minutes are up. + assert_eq!(attempts.get(), 7 + (20 * 60 - 63 - 1) / 60); + } + + #[test] + fn a_copy_or_paste_retries_at_most_once_a_second() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let (clock, attempts) = (Clock::new(), Cell::new(0)); + let mut cb = Reopen::new(&LOGGED); + let mut ask = |asker| { + let open = || { + attempts.set(attempts.get() + 1); + fail() + }; + let _ = cb.get(asker, clock.now(), open, name); + }; + // Long after the paste check gave up for a minute, a held Ctrl+V for 3 s at 30 a second. + for _ in 0..8 { + ask(Asker::Probe); + clock.advance(Duration::from_secs(70)); + } + let before = attempts.get(); + for _ in 0..90 { + ask(Asker::User); + clock.advance(Duration::from_millis(33)); + } + assert_eq!(attempts.get() - before, 3); + } + + #[test] + fn a_success_is_kept_and_ends_the_outage() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let clock = Clock::new(); + let mut cb = Reopen::new(&LOGGED); + assert!(cb.get(Asker::Probe, clock.now(), fail, name).is_none()); + assert!(LOGGED.load(Ordering::Relaxed)); + clock.advance(FIRST_WAIT); + assert_eq!(cb.get(Asker::Probe, clock.now(), || Ok(7), name).copied(), Some(7)); + assert!(!LOGGED.load(Ordering::Relaxed), "the recovery is logged"); + // Kept: not opened again, even where opening would now fail. + assert_eq!(cb.get(Asker::Probe, clock.now(), fail, name).copied(), Some(7)); + assert_eq!(cb.opened().copied(), Some(7)); + } + + #[test] + fn arboard_is_tried_before_the_wayland_core_protocol() { + let wayland_tried = Cell::new(false); + let wayland = |ok| { + wayland_tried.set(true); + if ok { Ok("wayland") } else { Err("not a Wayland window") } + }; + // Where arboard opens (data-control, X11) the core protocol isn't tried. + assert_eq!(first_open(|| Ok("arboard"), || wayland(true)), Ok("arboard")); + assert!(!wayland_tried.get()); + // The Flatpak on GNOME: no data-control, no X11. + assert_eq!(first_open(|| Err("no X11".into()), || wayland(true)), Ok("wayland")); + assert!(wayland_tried.get()); + // Neither: every reason is kept for the log. + assert_eq!( + first_open(|| Err("no X11".into()), || wayland(false)), + Err::<&str, _>("arboard: no X11; Wayland core protocol: not a Wayland window".into()) + ); + } + + #[test] + fn one_outage_is_logged_once_across_handles() { + static LOGGED: AtomicBool = AtomicBool::new(false); + let clock = Clock::new(); + let (mut ui, mut probe) = (Reopen::new(&LOGGED), Reopen::new(&LOGGED)); + assert!(probe.get(Asker::Probe, clock.now(), fail, name).is_none()); + assert!(LOGGED.load(Ordering::Relaxed)); + // The other handle's failure is the same outage: `swap` reports it already logged. + assert!(ui.get(Asker::User, clock.now(), fail, name).is_none()); + assert!(LOGGED.load(Ordering::Relaxed)); + assert!(probe.opened().is_none() && ui.opened().is_none()); + } + } +} + +/// The compositor's clipboard through the core data-device protocol (`wl_data_device`), on the +/// window's own Wayland connection: what Copy and Paste use where the compositor lacks the +/// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on +/// a Wayland session). Text only (smithay-clipboard), and only while the window has focus, as the +/// protocol has it. A read waits [`LOAD_WAIT`] at most: smithay-clipboard waits for the owner's +/// data with no limit, so reads run on a worker of their own. +#[cfg(target_os = "linux")] +mod wayland { + use std::sync::Arc; + use std::sync::mpsc; + use std::time::Duration; + + /// The longest a read waits for the selection's owner to send its text. + const LOAD_WAIT: Duration = Duration::from_secs(2); + /// What a read says once its worker has stopped. + const GONE: &str = "the clipboard's reader stopped"; + + pub struct TextClipboard { + /// Writes: a store only hands the text to smithay-clipboard's thread. + cb: smithay_clipboard::Clipboard, + /// Reads, on a worker with a second clipboard on the same connection. + loads: Loads, + /// Held as long as the clipboards: their connection is the window's. + _window: Arc, + } + + /// The read worker's clipboard and the window whose connection it uses, dropped in that order. + struct Loader { + cb: smithay_clipboard::Clipboard, + _window: Arc, + } + + impl Loader { + fn load(&self) -> Result { + self.cb.load().map_err(|e| e.to_string()) + } + } + + impl TextClipboard { + /// None when `window` isn't a Wayland window or the read worker can't start. + #[allow(unsafe_code)] + pub fn new(window: Arc) -> Option { + use winit::raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle}; + let RawDisplayHandle::Wayland(d) = window.display_handle().ok()?.as_raw() else { return None }; + let display = d.display.as_ptr(); + // SAFETY: the display is winit's open `wl_display`, which outlives `window`; each + // clipboard is held beside a clone of `window` and dropped before it. smithay-clipboard + // makes its own event queue on the display and doesn't close it. + let (cb, reader) = unsafe { (smithay_clipboard::Clipboard::new(display), smithay_clipboard::Clipboard::new(display)) }; + let loader = Loader { cb: reader, _window: window.clone() }; + // `loader.load()`, not `loader.cb.load()`: a closure moves only the fields it names, + // and the worker must hold the window as long as its clipboard. + let loads = Loads::spawn(move || loader.load())?; + Some(Self { cb, loads, _window: window }) + } + + pub fn get_text(&mut self) -> Result { + self.loads.get(LOAD_WAIT) + } + + pub fn set_text(&self, text: &str) { + self.cb.store(text); + } + } + + /// Reads made on a worker thread and waited for a bounded time: a selection owner that never + /// sends its data holds the worker, not the caller. + struct Loads { + requests: mpsc::Sender<()>, + answers: mpsc::Receiver>, + /// A read that timed out and hasn't answered yet: until it does, reads don't queue behind it. + pending: bool, + } + + impl Loads { + fn spawn(mut load: impl FnMut() -> Result + Send + 'static) -> Option { + let (requests, asked) = mpsc::channel::<()>(); + let (answer, answers) = mpsc::channel(); + let work = move || { + while asked.recv().is_ok() { + if answer.send(load()).is_err() { + break; + } + } + }; + std::thread::Builder::new().name("wayland-clipboard-read".into()).spawn(work).ok()?; + Some(Self { requests, answers, pending: false }) + } + + /// The text, or why there is none, after `wait` at most. + fn get(&mut self, wait: Duration) -> Result { + if self.pending { + match self.answers.try_recv() { + // The late answer of the read that timed out: stale by now. + Ok(_) => self.pending = false, + Err(mpsc::TryRecvError::Empty) => return Err("the clipboard's owner hasn't answered an earlier read".into()), + Err(mpsc::TryRecvError::Disconnected) => return Err(GONE.into()), + } + } + self.requests.send(()).map_err(|_| GONE.to_string())?; + match self.answers.recv_timeout(wait) { + Ok(text) => text, + Err(mpsc::RecvTimeoutError::Timeout) => { + self.pending = true; + Err(format!("the clipboard's owner didn't send its text within {wait:?}")) + } + Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()), + } + } + } + + #[cfg(test)] + mod tests { + use std::time::Instant; + + use super::*; + + #[test] + fn a_read_that_answers_in_time_gives_the_text() { + let mut loads = Loads::spawn(|| Ok("".into())).unwrap(); + assert_eq!(loads.get(Duration::from_secs(5)), Ok("".to_string())); + assert_eq!(loads.get(Duration::from_secs(5)), Ok("".to_string())); + } + + #[test] + fn an_owner_that_never_answers_holds_the_worker_not_the_caller() { + let (release, gate) = mpsc::channel::<()>(); + let mut calls = 0; + let mut loads = Loads::spawn(move || { + calls += 1; + if calls == 1 { + // The first owner sends nothing until released. + let _ = gate.recv(); + return Ok("stale".into()); + } + Ok("fresh".into()) + }) + .unwrap(); + let start = Instant::now(); + assert!(loads.get(Duration::from_millis(50)).is_err(), "the first read times out"); + // While it is unanswered, a read doesn't queue behind it or wait at all. + assert!(loads.get(Duration::from_secs(60)).is_err()); + assert!(start.elapsed() < Duration::from_secs(30), "no read waited past its bound"); + release.send(()).unwrap(); + // Once the late answer is in, it is dropped and a new read is made. + let text = (0..200).find_map(|_| { + std::thread::sleep(Duration::from_millis(10)); + loads.get(Duration::from_secs(5)).ok() + }); + assert_eq!(text.as_deref(), Some("fresh")); + } + + #[test] + fn a_read_after_the_worker_stops_says_so() { + let mut loads = Loads::spawn(|| Ok(String::new())).unwrap(); + // The worker ends when its answers can't be sent: drop them by hand. + let (_, dead) = mpsc::channel(); + drop(std::mem::replace(&mut loads.answers, dead)); + assert_eq!(loads.get(Duration::from_millis(50)), Err(GONE.to_string())); } } } diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index dc6ac19292..00f92405e3 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -140,38 +140,56 @@ pub fn backends(default: Backends, env_set: bool, opengl: bool) -> Backends { } /// Whether a Windows start lists OpenGL's adapters beside Direct3D 12's: only when it leaves an -/// adapter out (an earlier start crashed on it, or a restart failed on it) or DX12 lists none -/// (Windows 7). wgpu's OpenGL backend keeps a hidden window on a thread that pumps no messages, -/// and Windows waits on it when the input language changes, so the whole app hung on a switch to -/// another keyboard layout (#4150, gfx-rs/wgpu#10504), even drawing with DX12. +/// adapter out (an earlier start crashed on it, or a restart failed on it), when +/// `WGPU_ADAPTER_NAME` names one (it may be an OpenGL adapter), or when DX12 lists no hardware +/// adapter (Windows 7, or a GPU without a DX12 driver, which then draws through OpenGL as before +/// rather than on the CPU with WARP). wgpu's OpenGL backend keeps a hidden window on a thread that +/// pumps no messages, and Windows waits on it when the input language changes, so the whole app +/// hung on a switch to another keyboard layout (#4150, gfx-rs/wgpu#10504), even drawing with DX12. pub fn windows_opengl(left_out: &LeftOut) -> bool { - left_out.opengl_only || !left_out.adapters.is_empty() || !skipped().is_empty() || !dx12_lists_adapters() + opengl_needed(left_out, !skipped().is_empty(), std::env::var_os(NAME_ENV).is_some(), dx12_lists_hardware) } -/// Whether Direct3D 12 lists any adapter, WARP's software one included. A driver that crashes here -/// crashes a start while it lists the adapters, which the next start answers with OpenGL alone. +/// [`windows_opengl`], with a restart leaving adapters out (`skipping`) and an adapter named +/// (`named`): `dx12_hardware` is asked only when nothing else decides. +fn opengl_needed(left_out: &LeftOut, skipping: bool, named: bool, dx12_hardware: impl FnOnce() -> bool) -> bool { + left_out.opengl_only || !left_out.adapters.is_empty() || skipping || named || !dx12_hardware() +} + +/// Whether Direct3D 12 lists a hardware adapter; WARP, its software one, doesn't count. A driver +/// that crashes here crashes a start while it lists the adapters, which the next start answers with +/// OpenGL alone. #[cfg(windows)] -fn dx12_lists_adapters() -> bool { +fn dx12_lists_hardware() -> bool { let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); descriptor.backends = Backends::DX12; - // FXC is part of Windows, as for the window's own instance (#1194). - descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::Fxc; + // The shader compiler the window's own instance takes (#1194). + descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::from_env().unwrap_or(wgpu::Dx12Compiler::Fxc); let instance = wgpu::Instance::new(descriptor); - let found = pollster::block_on(instance.enumerate_adapters(Backends::DX12)).len(); - log::info!("Direct3D 12 lists {found} graphics adapters"); - found > 0 + let kinds: Vec = pollster::block_on(instance.enumerate_adapters(Backends::DX12)).iter().map(|a| a.get_info().device_type).collect(); + log::info!("Direct3D 12 lists these graphics adapters: {kinds:?}"); + any_hardware(&kinds) } #[cfg(not(windows))] -fn dx12_lists_adapters() -> bool { +fn dx12_lists_hardware() -> bool { false } -/// The largest texture side to ask the device for, which bounds the window's surface: the -/// adapter's own limit when it is above eframe's `default` (8192 px), so a window larger than -/// that keeps its surface (#1459). Never below `default`, which is what was asked for before. -pub fn surface_limit(default: u32, adapter: u32) -> u32 { - default.max(adapter) +/// Is one of the adapters of these kinds hardware, not software such as WARP? +#[cfg(any(windows, test))] +fn any_hardware(kinds: &[DeviceType]) -> bool { + kinds.iter().any(|k| *k != DeviceType::Cpu) +} + +/// The limits to ask the device for: what eframe `asked` for, lowered to what the `adapter` offers +/// wherever it offers less, so a GPU short of one of them still gets a device (#2105). The texture +/// side, which bounds the window's surface, is the adapter's own, above eframe's 8192 px when the +/// adapter allows more, so a window larger than that keeps its surface (#1459). +pub fn device_limits(asked: wgpu::Limits, adapter: &wgpu::Limits) -> wgpu::Limits { + let mut limits = asked.or_worse_values_from(adapter); + limits.max_texture_dimension_2d = adapter.max_texture_dimension_2d; + limits } /// One adapter, as [`adapter_order`] sees it. diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index e4824ecd9a..b1511a232a 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -5,11 +5,34 @@ fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate { } /// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that -/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing. +/// takes 16384 px textures. #[test] fn the_surface_may_be_as_large_as_the_adapter_allows() { - assert_eq!(surface_limit(8192, 16384), 16384); - assert_eq!(surface_limit(8192, 4096), 8192); + let adapter = wgpu::Limits { max_texture_dimension_2d: 16384, ..wgpu::Limits::default() }; + let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + assert_eq!(device_limits(asked, &adapter).max_texture_dimension_2d, 16384); +} + +/// #2105: a GPU that offers less than eframe asks for on any limit (here a Raspberry Pi 5's V3D 7.1: +/// 15 inter-stage variables on Vulkan, 4096 px textures on OpenGL) gets a device with what it +/// offers, instead of failing and leaving the window to the software rasterizer. A GPU that offers +/// more is asked for no more than before, except for the texture side. +#[test] +fn the_device_asks_for_no_more_than_the_adapter_offers() { + let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + let vulkan = wgpu::Limits { max_inter_stage_shader_variables: 15, max_texture_dimension_2d: 7680, ..wgpu::Limits::default() }; + let limits = device_limits(asked.clone(), &vulkan); + assert_eq!((limits.max_inter_stage_shader_variables, limits.max_texture_dimension_2d), (15, 7680)); + assert!(limits.check_limits(&vulkan), "{limits:?}"); + let gl = wgpu::Limits { max_texture_dimension_2d: 4096, ..wgpu::Limits::downlevel_webgl2_defaults() }; + let webgl2 = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::downlevel_webgl2_defaults() }; + let limits = device_limits(webgl2.clone(), &gl); + assert_eq!(limits.max_texture_dimension_2d, 4096); + assert!(limits.check_limits(&gl), "{limits:?}"); + let ample = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + assert_eq!(device_limits(asked.clone(), &le), asked); + let better = wgpu::Limits { max_inter_stage_shader_variables: 31, max_texture_dimension_2d: 8192, ..wgpu::Limits::default() }; + assert_eq!(device_limits(asked.clone(), &better), asked, "never more than eframe asked for"); } fn names(c: &[Candidate], order: &[usize]) -> Vec { @@ -472,6 +495,31 @@ fn windows_lists_opengl_once_a_start_leaves_an_adapter_out() { assert_eq!(listing.backends(backends(Backends::all(), false, true)), Backends::GL); } +/// OpenGL stays where it drew before #4150's fix: a GPU without a Direct3D 12 driver (DX12 lists +/// WARP alone) and an adapter `WGPU_ADAPTER_NAME` names; a start with a DX12 GPU lists DX12 alone. +#[test] +fn windows_lists_opengl_without_a_dx12_gpu_or_with_an_adapter_named() { + let start = LeftOut::default(); + let asked = std::cell::Cell::new(false); + let hardware = |found: bool| { + asked.set(true); + found + }; + assert!(!opengl_needed(&start, false, false, || hardware(true)), "a DX12 GPU: DX12 alone (#4150)"); + assert!(asked.replace(false)); + assert!(opengl_needed(&start, false, false, || hardware(false)), "WARP alone: the GPU draws through OpenGL, not the CPU"); + assert!(opengl_needed(&start, false, true, || hardware(true)), "a named adapter may be an OpenGL one"); + assert!(opengl_needed(&start, true, false, || hardware(true)), "a restart left an adapter out"); + let listing = LeftOut { opengl_only: true, ..LeftOut::default() }; + asked.set(false); + assert!(opengl_needed(&listing, false, false, || hardware(true))); + assert!(!asked.get(), "DX12 isn't listed once OpenGL must be"); + assert!(any_hardware(&[DeviceType::Cpu, DeviceType::IntegratedGpu])); + assert!(any_hardware(&[DeviceType::VirtualGpu])); + assert!(!any_hardware(&[DeviceType::Cpu]), "WARP"); + assert!(!any_hardware(&[]), "Windows 7"); +} + #[test] fn power_preference_follows_the_environment_then_the_preference() { assert_eq!(power_preference(None, None), AUTOMATIC); diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 4254d1591a..e25332b61a 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -255,6 +255,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .as_ref() .and_then(|w| w.window_handle().ok()) .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); + let (clip, clip_probe) = (parent.clone(), parent.clone()); let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); #[cfg(target_os = "macos")] let sampled_ui = ui.clone(); @@ -286,11 +287,12 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { fileio::write_file_with(p, fill).map_err(|e| e.to_string()) })), // Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event). - system_clipboard: Some(clipboard::system_clipboard()), + system_clipboard: Some(clipboard::system_clipboard(clip)), // Linux checks whether Paste has something to take on a background thread: an X11 clipboard // owner that never answers holds a read for up to 4 s. Windows only asks which formats the // clipboard holds and macOS asks the pasteboard server, so they check in line. - clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(clipboard::system_clipboard) as ClipboardProbeFactory), + // The probe's handle is made on its own thread, from the window (`Send`), not its raw display. + clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory), // Help → Discord / website / GitHub, the Discord button, About and Home links. open_url: Some(Box::new(|url: &str| { let _ = webbrowser::open(url); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index f02cbda187..980d3826bb 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1,7 +1,10 @@ //! VectorCraft desktop app. //! //! Usage: `vectorcraft [--control [--automation-read-root ]... [--automation-write-root ]...] -//! [--in-window-menus] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`) +//! [--in-window-menus] [--new-instance] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`) +//! +//! Files given while VectorCraft already runs open in that window, unless `--new-instance` is given +//! (Windows and Linux; `single_instance`). //! //! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on //! macOS instead of the macOS menu bar (`mac_menu`). @@ -16,6 +19,7 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] mod automation_args; +mod caps_lock; mod clipboard; #[cfg(feature = "wgpu")] mod compositor_gpu; @@ -45,11 +49,15 @@ mod open_documents; mod portal_save; mod prefs_dir; mod printing; +#[cfg(not(target_os = "macos"))] +mod single_instance; #[cfg(windows)] mod system_fonts; mod tablet; mod window; mod window_frame; +#[cfg(windows)] +mod windows_cores; mod windows_stylus; mod xwayland; @@ -87,6 +95,7 @@ use titlebar::{custom_titlebar, native_options}; struct App { app: VectorcraftApp, + host_caps_lock: caps_lock::HostCapsLock, /// Reported by wgpu when the window's graphics device is lost (a driver reset). graphics_loss: GraphicsLoss, /// The graphics device was lost and the unsaved changes are kept for Data Recovery. @@ -118,7 +127,9 @@ Options: (may be given more than once) --in-window-menus Keep the menus inside the window on macOS (or VECTORCRAFT_IN_WINDOW_MENUS=1) - --version Print the version and exit + --new-instance Open the files in a new window even when VectorCraft + already runs (Windows and Linux) + --version Print the version and exit -h, --help Print this help and exit Without a window (converting, scripting, the MCP server), use vectorcraft-cli: @@ -128,7 +139,7 @@ Without a window (converting, scripting, the MCP server), use vectorcraft-cli: fn main() -> std::process::ExitCode { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&craft_update::suite::VECTORCRAFT, &std::env::args_os().skip(1).collect::>()) { + if let Some(result) = craft_update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } // Before any thread starts: the pointer must find a cursor theme on Wayland (#2450). @@ -142,6 +153,7 @@ fn main() -> std::process::ExitCode { automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT")); let mut files = Vec::new(); let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"); + let mut new_instance = false; let mut args = std::env::args().skip(1); while let Some(a) = args.next() { match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) { @@ -154,6 +166,7 @@ fn main() -> std::process::ExitCode { } match a.as_str() { "--in-window-menus" => in_window_menus = true, + "--new-instance" => new_instance = true, "--version" => { println!("vectorcraft {}", env!("CARGO_PKG_VERSION")); return std::process::ExitCode::SUCCESS; @@ -183,7 +196,19 @@ fn main() -> std::process::ExitCode { }; // Before desktop services, so every start-up warning is recorded (`logging`). let logger = logging::install(); + // Files opened from the file manager while VectorCraft runs open in its window (#4892). Before + // the log file is attached: a launch that hands its files over leaves the running app's log be. + #[cfg(not(target_os = "macos"))] + let instance = match single_instance::start(control_port.is_some(), new_instance, &files) { + single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS, + single_instance::Start::Running(primary) => primary, + }; + #[cfg(target_os = "macos")] + let _ = new_instance; vectorcraft_ui_egui::i18n::detect_system_lang_in_background(); + // Before the first render: the cores the process may run on. + #[cfg(windows)] + windows_cores::install(); // Before the first font scan (the app's start): the fonts font services load (#579). #[cfg(windows)] system_fonts::install(); @@ -265,15 +290,15 @@ fn main() -> std::process::ExitCode { let options = native_options(custom_titlebar); // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux // Display Server › X11 opens the window through XWayland instead, where file drops work (#1151), - // and X11 (XWayland) When a Pen Is Attached does so when a pen is attached, where the pen draws (#2028). + // and the other choices do so when a pen is attached, where the pen draws (#2028, #4967). #[cfg(target_os = "linux")] let options = { let mut options = options; let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str); if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { if xwayland::x11_libraries_found() { - if pref == Some("x11WithPen") { - log::info!("pen found: opening the window through XWayland (Preferences › Performance › Linux Display Server)"); + if pref != Some("x11") { + log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); } else { log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); } @@ -321,14 +346,15 @@ fn main() -> std::process::ExitCode { // losing the device before the first frame (#1194). `WGPU_DX12_COMPILER` picks another. create.instance_descriptor.backend_options.dx12.shader_compiler = eframe::wgpu::Dx12Compiler::from_env().unwrap_or(eframe::wgpu::Dx12Compiler::Fxc); - // The window's surface may be as large as the adapter allows, not eframe's fixed - // 8192 px: a window stretched over several monitors, or grown by a display scale - // change, otherwise fails to configure its surface and the app closes (#1459). + // The device asks for no more than the adapter offers, so a GPU short of one of + // eframe's limits still gets a device (#2105). The window's surface may be as large as + // the adapter allows, not eframe's fixed 8192 px: a window stretched over several + // monitors, or grown by a display scale change, otherwise fails to configure its + // surface and the app closes (#1459). let device = create.device_descriptor.clone(); create.device_descriptor = std::sync::Arc::new(move |adapter: &eframe::wgpu::Adapter| { let mut descriptor = device(adapter); - let limit = &mut descriptor.required_limits.max_texture_dimension_2d; - *limit = gpu::surface_limit(*limit, adapter.limits().max_texture_dimension_2d); + descriptor.required_limits = gpu::device_limits(descriptor.required_limits, &adapter.limits()); descriptor }); } @@ -452,7 +478,10 @@ fn main() -> std::process::ExitCode { } } #[cfg(not(target_os = "macos"))] - let _ = in_window_menus; + { + let _ = in_window_menus; + single_instance::set_ui(&cc.egui_ctx); + } app.services.native_input_hook = native_input_hook(&app); file_access::unconfined(|| open_files(&mut app, files)); // The first frame is due from now (`gpu::watch_first_frame`). @@ -461,6 +490,7 @@ fn main() -> std::process::ExitCode { // The content and the pointer stay aligned on Windows (#1758). let window_frame = window_frame::service(cc, custom_titlebar); Ok(Box::new(App { + host_caps_lock: caps_lock::HostCapsLock::new(winit_window.as_deref()), app, graphics_loss, graphics_lost: false, @@ -473,6 +503,10 @@ fn main() -> std::process::ExitCode { }), ) }); + // The window is gone: later launches start their own app, including the one a graphics + // failure starts again below. + #[cfg(not(target_os = "macos"))] + drop(instance); #[cfg(feature = "wgpu")] let outcome = gpu::finish(outcome, &startup); #[cfg(not(feature = "wgpu"))] diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index 56ea30f21f..728fe9ba8d 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -84,24 +84,200 @@ pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option(&b).ok()); + let merged = match (base.as_ref(), on_disk) { + (Some(base), Some(on_disk)) => merge_changes(base, &mine, on_disk), + _ => mine.clone(), + }; + let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new("."))); + let Ok(bytes) = serde_json::to_vec_pretty(&merged) else { return }; + // Preferences are best effort: a failed write keeps the previous file, and the changes are + // tried again on the next save. + if fileio::write_atomic(&p, &bytes).is_ok() { + set_saved_base(Some(mine)); } } +/// How often [`save_prefs_soon`] looks for changes to save. +const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(2); + +/// Save the preferences at most every [`SAVE_EVERY`] while the app runs, when something changed: +/// the workspace, panels, toolbars and the other UI settings kept only in the UI state were saved +/// only on quitting, so a session ended any other way (the window closed by the system, the +/// process ended or crashing) started the next one from the settings before it (#4625). +pub(crate) fn save_prefs_soon(app: &VectorcraftApp) { + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + let Ok(mut last) = LAST.lock() else { return }; + if last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + return; + } + *last = Some(std::time::Instant::now()); + drop(last); + save_prefs(app); +} + +/// The preferences as this window last read or saved them (`None`: not read yet). +static SAVED_BASE: std::sync::Mutex> = std::sync::Mutex::new(None); + +fn saved_base() -> Option { + SAVED_BASE.lock().ok().and_then(|b| b.clone()) +} + +fn set_saved_base(value: Option) { + if let Ok(mut b) = SAVED_BASE.lock() { + *b = value; + } +} + +/// Fields of the UI state that a start resets ([`vectorcraft_ui_egui::UiState::sanitized`]): a +/// change to them alone isn't saved, and they are never merged over another window's. +const PASSING: &[&str] = &["status", "dialog", "flyout", "palette_open", "palette_query", "about", "open_panel"]; + +/// Do `a` and `b` hold the same preferences, leaving out what a start resets ([`PASSING`])? +fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool { + match (a.as_object(), b.as_object()) { + (Some(a), Some(b)) => { + let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).filter(|k| !PASSING.contains(&k.as_str())).collect(); + keys.into_iter().all(|k| a.get(k) == b.get(k)) + } + _ => a == b, + } +} + +/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI +/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change +/// different settings keep both. A field both changed takes this window's value (it saves last). +fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: serde_json::Value) -> serde_json::Value { + use serde_json::Value; + let (Some(base), Some(mine), Value::Object(mut out)) = (base.as_object(), mine.as_object(), on_disk) else { + return mine.clone(); + }; + let keys: std::collections::BTreeSet<&String> = base.keys().chain(mine.keys()).collect(); + for key in keys { + if PASSING.contains(&key.as_str()) { + if let Some(v) = mine.get(key) { + out.entry(key.clone()).or_insert_with(|| v.clone()); + } + continue; + } + let (was, now) = (base.get(key), mine.get(key)); + if was == now { + continue; + } + if key == "engine_prefs" + && let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key)) + { + let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect(); + for name in names { + match (was.get(name), now.get(name)) { + (a, b) if a == b => {} + (_, Some(v)) => { + theirs.insert(name.clone(), v.clone()); + } + (_, None) => { + theirs.remove(name); + } + } + } + continue; + } + match now { + Some(v) => { + out.insert(key.clone(), v.clone()); + } + None => { + out.remove(key); + } + } + } + Value::Object(out) +} + /// The preferences file's contents: the UI state with the engine preferences. +#[cfg(test)] pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result> { + serde_json::to_vec_pretty(&prefs_value(app)?) +} + +/// [`prefs_bytes`] as JSON. +fn prefs_value(app: &VectorcraftApp) -> serde_json::Result { let mut ui = app.ui.clone(); ui.engine_prefs = app.session.prefs.to_json(); - serde_json::to_vec_pretty(&ui) + serde_json::to_value(&ui) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::{merge_changes, same_lasting}; + + /// Two windows open at once (#4625): the one that saves last keeps the other's changes and + /// adds its own, instead of putting back the preferences it started from. + #[test] + fn a_window_saves_only_what_it_changed_over_another_windows_save() { + let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}}); + // The other window switched the workspace and the accent, and saved. + let on_disk = json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.0}}); + // This one changed only the UI scaling. + let mine = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.25}}); + let merged = merge_changes(&base, &mine, on_disk); + assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}})); + } + + #[test] + fn a_setting_both_windows_changed_takes_the_last_saved() { + let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}}); + let on_disk = json!({"workspace": "Painting", "engine_prefs": {"uiAccent": "violet"}}); + let mine = json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}}); + assert_eq!(merge_changes(&base, &mine, on_disk), json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}})); + } + + #[test] + fn fields_added_or_removed_by_this_window_are_saved() { + let base = json!({"docking": {"root": 1}, "engine_prefs": {"old": 1}}); + let on_disk = json!({"docking": {"root": 1}, "recent_files": ["a.svg"], "engine_prefs": {"old": 1}}); + let mine = json!({"dock_width": 300.0, "engine_prefs": {"new": 2}}); + assert_eq!(merge_changes(&base, &mine, on_disk), json!({"dock_width": 300.0, "recent_files": ["a.svg"], "engine_prefs": {"new": 2}})); + } + + /// The status line and open dialogs reset at start: they don't make a save, and they don't + /// replace another window's. + #[test] + fn what_a_start_resets_is_left_out() { + let base = json!({"status": "", "dialog": null, "workspace": "Essentials"}); + let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials"}); + assert!(same_lasting(&base, &mine)); + let on_disk = json!({"status": "Opened", "dialog": null, "workspace": "Painting"}); + let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials", "toolbar": false}); + let merged = merge_changes(&base, &mine, on_disk); + assert_eq!(merged, json!({"status": "Opened", "dialog": null, "workspace": "Painting", "toolbar": false})); + assert!(!same_lasting(&base, &mine)); + } + + #[test] + fn a_file_that_is_not_an_object_is_replaced() { + let base = json!({"workspace": "Essentials"}); + let mine = json!({"workspace": "Painting"}); + assert_eq!(merge_changes(&base, &mine, json!([1, 2])), mine); + } } diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs new file mode 100644 index 0000000000..b8df2bb5a1 --- /dev/null +++ b/apps/vectorcraft/src/single_instance.rs @@ -0,0 +1,386 @@ +//! One app per user (#4892): a file opened from the file manager (double-click, Open With, a drop +//! on the executable) while VectorCraft runs opens as a new document tab in the running app, which +//! comes to the front, instead of in a second app. +//! +//! The running app (the primary) listens on a loopback port and records the port and two random +//! tokens in `instance.json` next to the preferences (owner-only on Unix; on Windows the settings +//! folder is the user's own). A later launch with files connects; the primary greets it with +//! `hello`, which only a process that could read the file (or talk to the primary) knows; only then +//! does the launch send `token` and the absolute paths of its files, one JSON line. The primary +//! checks the token, keeps the paths that are existing files, acknowledges and opens them; the +//! launch exits. Anything else (no file, no listener, a wrong greeting, no answer) starts the launch +//! as its own app, which replaces a stale file. Nothing received is ever run. +//! +//! Runs that start many apps side by side (`--control`, `VECTORCRAFT_NO_PREFS`) neither forward +//! nor listen, and `--new-instance` opens a launch's files in an app of its own. macOS hands files +//! opened from Finder to the running app itself (`open_documents`), so this is off there. + +use std::fs::{self, OpenOptions}; +use std::hash::{BuildHasher as _, RandomState}; +use std::io::{self, BufRead as _, BufReader, Read as _, Write as _}; +use std::net::{Ipv4Addr, TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock, PoisonError}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use super::prefs::{prefs_enabled, prefs_path}; + +/// The endpoint file, next to the preferences. +const FILE_NAME: &str = "instance.json"; +/// The longest message either side reads, and the longest endpoint file. +const MAX_MESSAGE: u64 = 64 * 1024; +/// The most files one launch hands over. +const MAX_FILES: usize = 256; +/// A live primary's kernel accepts at once, even while its window is busy; a stale port on Windows +/// would otherwise retry for about two seconds. +const CONNECT_TIMEOUT: Duration = Duration::from_millis(500); +/// How long the primary waits on one launch; it serves launches one at a time. +const SERVER_TIMEOUT: Duration = Duration::from_secs(2); +/// How long a launch waits on the primary: longer than a launch served before it can take. +const CLIENT_TIMEOUT: Duration = Duration::from_secs(5); + +/// Paths handed over by later launches that the UI hasn't opened yet. +static PENDING: Mutex> = Mutex::new(Vec::new()); +/// The UI to wake when files arrive (unset until the window exists; the first frame opens them). +static UI: OnceLock = OnceLock::new(); + +/// What this launch does about an app already running. +pub enum Start { + /// The running app took the files: this launch exits. + Forwarded, + /// This launch runs; `Some` while it is the app later launches hand their files to. + Running(Option), +} + +/// Hand `files` to the app already running, or become the app later launches hand theirs to. +/// `automation`: started with `--control`. +pub fn start(automation: bool, new_instance: bool, files: &[String]) -> Start { + if automation || !prefs_enabled() { + return Start::Running(None); + } + let Some(path) = prefs_path().and_then(|p| Some(p.parent()?.join(FILE_NAME))) else { return Start::Running(None) }; + // With nothing to hand over, the same exchange only asks whether an app is running. + let send: &[String] = if new_instance { &[] } else { files }; + match forward(&path, send) { + Ok(()) if send.is_empty() => Start::Running(None), + Ok(()) => Start::Forwarded, + Err(e) => { + log::debug!("no running VectorCraft to hand files to ({e})"); + Start::Running(listen(&path, queue)) + } + } +} + +/// Wake `ctx` when files arrive from later launches. +pub fn set_ui(ctx: &egui::Context) { + // Set once; a second call would hand over the same context. + let _ = UI.set(ctx.clone()); +} + +/// The paths later launches handed over since the last call. +pub fn take() -> Vec { + std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)) +} + +fn queue(files: Vec) { + PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(files); + if let Some(ctx) = UI.get() { + ctx.request_repaint(); + } +} + +/// This app is the one recorded in the endpoint file; dropping it removes the file, unless a later +/// app has replaced it since. +pub struct Primary { + path: PathBuf, + token: String, +} + +impl Drop for Primary { + fn drop(&mut self) { + if read_endpoint(&self.path).is_some_and(|e| e.token == self.token) { + // Best effort: a file left behind is stale, and the next launch replaces it. + let _ = fs::remove_file(&self.path); + } + } +} + +struct Endpoint { + port: u16, + token: String, + hello: String, +} + +fn invalid(why: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, why) +} + +fn read_endpoint(path: &Path) -> Option { + let mut text = String::new(); + fs::File::open(path).ok()?.take(MAX_MESSAGE).read_to_string(&mut text).ok()?; + let v: Value = serde_json::from_str(&text).ok()?; + let port = u16::try_from(v.get("port")?.as_u64()?).ok().filter(|p| *p != 0)?; + Some(Endpoint { port, token: v.get("token")?.as_str()?.to_owned(), hello: v.get("hello")?.as_str()?.to_owned() }) +} + +/// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok` +/// once it acknowledged them. +fn forward(path: &Path, files: &[String]) -> io::Result<()> { + let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?; + let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::>>()?; + let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?; + stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; + stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; + // The token and the paths go only to a listener that knows the greeting. + if !same(read_message(&stream)?.get("hello"), &endpoint.hello) { + return Err(invalid("the listener isn't VectorCraft")); + } + write_message(&stream, &json!({ "token": endpoint.token, "files": files }))?; + match read_message(&stream)?.get("ok") { + Some(Value::Bool(true)) => Ok(()), + _ => Err(invalid("refused")), + } +} + +/// Listen for later launches and record this app at `path`; each launch's files go to `deliver`. +/// `None` when that fails (logged): the app then runs on its own, as before. +fn listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> Option { + try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok() +} + +fn try_listen(path: &Path, deliver: impl Fn(Vec) + Send + 'static) -> io::Result { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; + let port = listener.local_addr()?.port(); + let (token, hello) = random_tokens(); + write_endpoint(path, &json!({ "port": port, "token": token, "hello": hello }))?; + // From here on a failure removes the file again. + let primary = Primary { path: path.to_path_buf(), token: token.clone() }; + std::thread::Builder::new().name("open-files-listener".into()).spawn(move || { + for stream in listener.incoming() { + match stream.and_then(|s| receive(&s, &hello, &token)) { + Ok(files) if files.is_empty() => {} + Ok(files) => deliver(files), + Err(e) => { + log::warn!("refused files from another launch: {e}"); + // An accept that keeps failing (out of handles) doesn't spin. + std::thread::sleep(Duration::from_millis(50)); + } + } + } + })?; + Ok(primary) +} + +/// Serve one launch: greet it, check its token, keep the paths that are existing files. +fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result> { + stream.set_read_timeout(Some(SERVER_TIMEOUT))?; + stream.set_write_timeout(Some(SERVER_TIMEOUT))?; + write_message(stream, &json!({ "hello": hello }))?; + let message = read_message(stream)?; + if !same(message.get("token"), token) { + return Err(invalid("wrong token")); + } + let files = message.get("files").and_then(Value::as_array).ok_or_else(|| invalid("no file list"))?; + if files.len() > MAX_FILES { + return Err(invalid("too many files")); + } + let files = files + .iter() + .filter_map(Value::as_str) + .filter(|f| { + let p = Path::new(f); + let ok = p.is_absolute() && p.is_file(); + if !ok { + log::warn!("another launch named {f}, which isn't a file"); + } + ok + }) + .map(str::to_owned) + .collect(); + write_message(stream, &json!({ "ok": true }))?; + Ok(files) +} + +/// One JSON line of at most [`MAX_MESSAGE`] bytes. Each side sends one line and waits for the +/// other's, so nothing read past it is lost. +fn read_message(stream: &TcpStream) -> io::Result { + let mut line = Vec::new(); + BufReader::new(stream.take(MAX_MESSAGE)).read_until(b'\n', &mut line)?; + if line.last() != Some(&b'\n') { + return Err(invalid("message too long or cut short")); + } + serde_json::from_slice(&line).map_err(|e| invalid(&e.to_string())) +} + +fn write_message(mut stream: &TcpStream, message: &Value) -> io::Result<()> { + let mut line = serde_json::to_vec(message).map_err(io::Error::other)?; + line.push(b'\n'); + stream.write_all(&line) +} + +/// `given` is the string `expected`, compared in constant time. +fn same(given: Option<&Value>, expected: &str) -> bool { + given + .and_then(Value::as_str) + .is_some_and(|g| g.len() == expected.len() && g.bytes().zip(expected.bytes()).fold(0, |acc, (a, b)| acc | (a ^ b)) == 0) +} + +/// Two unrelated 128-bit hex tokens. `RandomState` is keyed from the system's random numbers, and +/// its keyed hash of distinct values gives unpredictable, independent output (no crate needed). +fn random_tokens() -> (String, String) { + let keyed = RandomState::new(); + let token = |a: u8, b: u8| format!("{:016x}{:016x}", keyed.hash_one(a), keyed.hash_one(b)); + (token(1, 2), token(3, 4)) +} + +/// Replace `path` with `endpoint` at once (a temporary file renamed over it), readable only by the +/// user on Unix. +fn write_endpoint(path: &Path, endpoint: &Value) -> io::Result<()> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir)?; + } + let tmp = path.with_extension(format!("{}.tmp", std::process::id())); + // A leftover of an earlier app with the same process id; `create_new` sets the mode below. + let _ = fs::remove_file(&tmp); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let bytes = serde_json::to_vec(endpoint).map_err(io::Error::other)?; + let written = options.open(&tmp).and_then(|mut f| f.write_all(&bytes)).and_then(|()| fs::rename(&tmp, path)); + if written.is_err() { + // Best effort: the temporary file is all there is to clean up. + let _ = fs::remove_file(&tmp); + } + written +} + +#[cfg(test)] +mod tests { + use std::sync::mpsc; + + use super::*; + + /// A fresh folder for one test, with an existing file in it. + fn folder(name: &str) -> (PathBuf, PathBuf, String) { + let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let file = dir.join("a b.svg"); + fs::write(&file, "").unwrap(); + let file = file.to_string_lossy().into_owned(); + (dir.join(FILE_NAME), dir, file) + } + + fn primary(path: &Path) -> (Primary, mpsc::Receiver>) { + let (tx, rx) = mpsc::channel(); + let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap(); + (primary, rx) + } + + /// Connects as a launch would and sends `message` after the greeting; what came back. + fn send_raw(path: &Path, message: &[u8]) -> io::Result { + let endpoint = read_endpoint(path).unwrap(); + let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap(); + stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); + assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello)); + (&stream).write_all(message)?; + read_message(&stream) + } + + #[test] + fn a_launch_hands_its_files_to_the_running_app() { + let (path, dir, file) = folder("forward"); + let (primary, rx) = primary(&path); + let missing = dir.join("missing.svg").to_string_lossy().into_owned(); + forward(&path, &[file.clone(), missing]).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out"); + // An empty list only asks whether the app runs: nothing is delivered. + forward(&path, &[]).unwrap(); + forward(&path, std::slice::from_ref(&file)).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + drop(primary); + assert!(!path.exists(), "the endpoint file goes with the app"); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_wrong_token_garbage_and_oversized_messages_are_refused() { + let (path, dir, file) = folder("refused"); + let (_primary, rx) = primary(&path); + let token = read_endpoint(&path).unwrap().token; + let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] })); + assert!(send_raw(&path, wrong.as_bytes()).is_err()); + assert!(send_raw(&path, b"not json\n").is_err()); + assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err()); + let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] })); + assert!(send_raw(&path, many.as_bytes()).is_err()); + let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] })); + assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true })); + assert!(rx.try_recv().is_err(), "nothing was delivered"); + // The listener still serves a launch with the right token. + forward(&path, std::slice::from_ref(&file)).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_stale_endpoint_file_is_ignored_and_replaced() { + let (path, dir, file) = folder("stale"); + // No listener on the recorded port any more. + let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port(); + write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); + assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + // A listener that doesn't know the greeting gets neither the token nor the paths. + let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let port = impostor.local_addr().unwrap().port(); + write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); + let heard = std::thread::spawn(move || { + let (stream, _) = impostor.accept().unwrap(); + write_message(&stream, &json!({ "hello": "x" })).unwrap(); + stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap(); + read_message(&stream).ok() + }); + assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + assert!(heard.join().unwrap().is_none()); + // Garbage in the file is no endpoint either. + fs::write(&path, b"\xff not json").unwrap(); + assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + // A new primary replaces the stale file. + let (_primary, rx) = primary(&path); + forward(&path, std::slice::from_ref(&file)).unwrap(); + assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() { + let (path, dir, _) = folder("replaced"); + let (first, _rx1) = primary(&path); + let (_second, _rx2) = primary(&path); + let second_token = read_endpoint(&path).unwrap().token; + drop(first); + assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token)); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn tokens_are_random_and_distinct() { + let (a, b) = random_tokens(); + let (c, _) = random_tokens(); + assert_eq!(a.len(), 32); + assert!(a != b && a != c); + } + + #[cfg(unix)] + #[test] + fn the_endpoint_file_is_the_users_alone() { + use std::os::unix::fs::PermissionsExt as _; + let (path, dir, _) = folder("mode"); + let _primary = primary(&path); + assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = fs::remove_dir_all(dir); + } +} diff --git a/apps/vectorcraft/src/windows_cores.rs b/apps/vectorcraft/src/windows_cores.rs new file mode 100644 index 0000000000..b35c0876cf --- /dev/null +++ b/apps/vectorcraft/src/windows_cores.rs @@ -0,0 +1,40 @@ +//! Windows: the cores the process may run on, from its affinity mask, for the renderer's worker +//! count (`vectorcraft_render::set_usable_cores`). `available_parallelism` counts every processor +//! in the machine, also when the process may run on fewer (started with `start /affinity`, or +//! pinned by a launcher). The desktop app and `vectorcraft-cli` (exports, MCP) both install it; the +//! CLI shares this file. +//! +//! `GetProcessAffinityMask` is a C API with no safe binding, hence the scoped `unsafe_code` +//! allowance. +#![allow(unsafe_code)] + +use windows::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask}; + +/// Tells the renderer how many cores the process may run on. +pub fn install() { + vectorcraft_render::set_usable_cores(usable_cores()); +} + +/// The number of cores in the process's affinity mask, or `None` when Windows reports none (a +/// process with threads in more than one processor group). +fn usable_cores() -> Option { + let (mut process, mut system) = (0usize, 0usize); + // SAFETY: `GetCurrentProcess` returns a pseudo-handle that needs no closing, and both pointers + // point at live `usize`s for the length of the call. + unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut process, &mut system) }.ok()?; + (process != 0).then(|| process.count_ones() as usize) +} + +#[cfg(test)] +mod tests { + /// The mask Windows reports for this process gives at least one core and no more than the + /// machine has. (A child process started with `start /affinity` would test a one-core mask + /// end to end, but a process spawned while other tests hold sockets inherits them and resets + /// their connections; `automatic_threads` covers the one-core count.) + #[test] + fn the_affinity_mask_gives_the_cores_the_process_may_use() { + let cores = super::usable_cores().unwrap(); + let all = std::thread::available_parallelism().unwrap().get(); + assert!((1..=all).contains(&cores), "{cores} of {all}"); + } +} diff --git a/apps/vectorcraft/src/xwayland.rs b/apps/vectorcraft/src/xwayland.rs index 509a700569..38b210c05e 100644 --- a/apps/vectorcraft/src/xwayland.rs +++ b/apps/vectorcraft/src/xwayland.rs @@ -1,8 +1,10 @@ //! Linux: Preferences › Performance › Linux Display Server › X11 opens the window through XWayland //! on a Wayland session, where dropped files arrive (winit 0.30 has no Wayland drag and drop, -//! #1151). X11 (XWayland) When a Pen Is Attached does so only when a pen is attached as the app -//! starts: winit 0.30 doesn't bind the Wayland tablet protocol, and XWayland hands the pen to X11 -//! windows as a pointer (#2028). Only when XWayland can run the window: an X display is set and +//! #1151). Automatic and X11 (XWayland) When a Pen Is Attached do so only when a pen is attached +//! as the app starts, as PhotoCraft does: winit 0.30 doesn't bind the Wayland tablet protocol, so +//! on native Wayland the pen moves only the compositor's cursor, and XWayland hands the pen to X11 +//! windows as a pointer (#2028, #4967). `VECTORCRAFT_NATIVE_WAYLAND=1` keeps a pen's window on +//! Wayland. Only when XWayland can run the window: an X display is set and //! the X11 libraries winit loads at runtime are installed. Otherwise the window opens on Wayland, //! so a missing library never keeps the app from starting. //! @@ -21,16 +23,17 @@ const X11_LIBS: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; /// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or -/// `x11WithPen` chosen and `pen` finding a pen; a Wayland session (winit picks Wayland whenever -/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only for -/// `x11WithPen`, after the session checks. +/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and +/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever +/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after +/// the other checks. pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { let set = |name: &str| var(name).is_some_and(|v| !v.is_empty()); let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY"); + let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0"); match pref { Some("x11") => session, - Some("x11WithPen") => session && pen(), - _ => false, + _ => session && !native_wayland && pen(), } } @@ -149,27 +152,35 @@ mod tests { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); assert!(wanted(Some("x11"), &wayland, no_probe)); assert!(wanted(Some("x11"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), no_probe)); - assert!(!wanted(Some("automatic"), &wayland, no_probe)); - assert!(!wanted(None, &wayland, no_probe)); - assert!(!wanted(Some("wayland"), &wayland, no_probe)); + assert!(!wanted(Some("automatic"), &wayland, || false)); + assert!(!wanted(None, &wayland, || false)); // An X11 session already opens on X11; without an X display there is no XWayland to use. assert!(!wanted(Some("x11"), env(&[("DISPLAY", ":0")]), no_probe)); assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe)); assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe)); } - /// X11 (XWayland) When a Pen Is Attached (#2028): XWayland on a Wayland session with an X - /// display when a pen is found, the session's own display server otherwise. The pen check - /// runs only on such a session. + /// Automatic and X11 (XWayland) When a Pen Is Attached (#2028, #4967): XWayland on a Wayland + /// session with an X display when a pen is found, where the pen reaches the window, the + /// session's own display server otherwise. The pen check runs only on such a session, and + /// `VECTORCRAFT_NATIVE_WAYLAND` keeps Wayland. #[test] - fn the_pen_choice_opens_xwayland_only_with_a_pen() { + fn a_pen_opens_xwayland_unless_native_wayland_is_asked_for() { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); - assert!(wanted(Some("x11WithPen"), &wayland, || true)); - assert!(wanted(Some("x11WithPen"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true)); - assert!(!wanted(Some("x11WithPen"), &wayland, || false)); - assert!(!wanted(Some("x11WithPen"), env(&[("DISPLAY", ":0")]), no_probe)); - assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe)); - assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe)); + let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]); + let not_native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "0")]); + for pref in [Some("automatic"), None, Some("x11WithPen")] { + assert!(wanted(pref, &wayland, || true), "{pref:?}"); + assert!(wanted(pref, env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true), "{pref:?}"); + assert!(!wanted(pref, &wayland, || false), "{pref:?}"); + assert!(!wanted(pref, env(&[("DISPLAY", ":0")]), no_probe), "{pref:?}"); + assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe), "{pref:?}"); + assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe), "{pref:?}"); + assert!(!wanted(pref, &native, no_probe), "{pref:?}"); + assert!(wanted(pref, ¬_native, || true), "{pref:?}"); + } + // The X11 choice opens XWayland with or without a pen; the opt-out is for the pen only. + assert!(wanted(Some("x11"), &native, no_probe)); } /// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 0b8fce9215..5f57c94a62 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -16,9 +16,7 @@ head-and-shoulders portrait on a full-bleed field, no frame or roundel, with the **Tile:** `viewBox="0 0 512 512"`, a rounded square with `rx=112`, clipped. The macOS files add Apple's transparent margin (tile = 824/1024 of the canvas); Windows and Linux use the tile edge to edge. -**Provenance:** the owner's original ArtCraft drawing (2880 px, keyed to the palette), vectorised with -craftrules `assets/logo-options/_tools/vectorize_tile.py`. The drawing is kept in craftrules at -`craftrules/assets/app-icons/vectorcraft/source.png`, not here. `vectorcraft.svg` is the canonical +**Provenance:** the owner's original ArtCraft drawing, vectorised. `vectorcraft.svg` is the canonical artwork. Licence: see `LICENSE.txt`. ## Files diff --git a/contributors/people.toml b/contributors/people.toml index 8578d13f18..f3c8629b71 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -1,13 +1,10 @@ -# Contributor names for the About window (craftrules standards/contributors.md). +# Contributor names for the About window. # # Everyone who contributes is credited by GitHub username automatically. Anything more is up to # you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a # maintainer may add a person only when that person asked, recording where in consent_source. # -# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \ -# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name] -# -# Or copy this block, replacing your-github-username (every field is optional): +# Copy this block, replacing your-github-username (every field is optional): # # [people.your-github-username] # real_name = "Your Name" # shown when the viewer picks "Real name" @@ -17,6 +14,11 @@ # To remove your names, delete your entry (or set fields empty) in a PR. The next # contributors.py run, and the next build, drop them. +[people.el-j] +real_name = "Fabian Althaus" +display_name = "faff (el-j)" +sync_github_name = false + [people.lollinoo] sync_github_name = true @@ -172,3 +174,18 @@ sync_github_name = false [people.krosk93] sync_github_name = true + +[people.ashokram-si] +real_name = "Ashok Ram" + +[people.dylanmtaylor] +sync_github_name = true + +[people.marshiyar] +display_name = "Arshiya" +real_name = "Arshiya Rahgozar" +sync_github_name = false + +[people.WadahBadawi] +display_name = "Wadah Badawi" +sync_github_name = true diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 62e2974d26..fd2d6dc71a 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -17,12 +17,13 @@ Affinity files. | Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | paths (multi-subpath curves fill even-odd) | | Rectangles with corner radii (relative or absolute, locked or per corner) and round or straight corners, ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids | paths | | Compound shapes (`Comp`, add and subtract) | one even-odd path | -| A shape or curve with children clips them | clip group whose clipping path keeps its fill (behind) and stroke (over) | +| A shape, curve or text with children clips them | clip group whose clipping path keeps its fill (behind) and stroke (over) | | Vector masks (`AdCh` curves and shapes) | clip group | | Pixel masks (`MRst`, attached or as a layer in a group) | opacity mask | | Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | fill appearance (alpha as fill opacity) | | Linear, elliptical and radial gradients with Affinity's midpoint bias | gradients (the bias as the midpoint where the blend is half way) | | Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill; a stroke whose style is None (every shape stores one, black and 1 px) is left out | stroke appearance | +| A stroke's pressure curve (`LDeP`: position along the path against width) | the stroke's width profile, the curve sampled at 2 to 8 points per segment (256 segments at most), widths up to the full weight | | Fill layers (`FRst`) | filled rectangles | | Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, underline, strikethrough, size, tracking, horizontal scale, fixed leading, colour, outlined characters, first baseline; each paragraph's alignment, indents, space before and after, fixed and automatic leading; frame text sized by its text scale (`FTxS`), not its frame's transform | point type and area type, one paragraph style per paragraph; artistic text whose paragraphs align differently keeps them aligned within its longest line (by indents), as Affinity draws it; a frame's first line hangs from its capitals' tops, and a frame whose last lines' descenders hang out of it is made just tall enough to show them; line breaks inside a paragraph become paragraphs without spacing between them; table cells place their text as Affinity does (centred from the capitals' tops to the last baseline, reaching out of a cell too short for it) | | Tables (`TxtT`): grid, cell text, merged cells, cell insets and vertical alignment, the line on every cell edge | a group of area type per cell and a stroked line per edge (VectorCraft has no tables) | @@ -33,7 +34,7 @@ Affinity files. | Opacity, visibility, lock, names, the blend modes VectorCraft has | the same | Everything else is reported in the import warnings, one line per kind with a count, never -dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush and pressure strokes, +dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read or that go past the million points one document may hold, transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial), special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner types other than round or straight, stars with rounded points, several fills or strokes on one object (the diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index 8e84e48077..bb1c45746b 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -169,6 +169,88 @@ fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option Option> { + let s = r.s; + let data = s.obj(crvd, b"Data")?; + let records = s.positional(data).find_map(|v| if let Value::Array(a) = v { Some(a) } else { None })?; + // Every segment takes at least an anchor record. + if records.len() > MAX_PRESSURE_SEGMENTS * 3 + 1 { + return None; + } + let curve = subpath(&anchors(records)?, false, None)?; + if curve.segments.len() > MAX_PRESSURE_SEGMENTS { + return None; + } + let steps = u32::try_from((PRESSURE_POINTS / curve.segments.len().max(1)).clamp(2, 8)).unwrap_or(2); + let mut samples = vec![(curve.start.x, curve.start.y)]; + let mut from = curve.start; + for [c1, c2, to] in &curve.segments { + let mut ts: Vec = (1..=steps).map(|i| f64::from(i) / f64::from(steps)).collect(); + ts.extend(turning_points(from.y, c1.y, c2.y, to.y).into_iter().flatten()); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + for t in ts { + let u = 1.0 - t; + let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; + samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y))); + } + from = *to; + } + let mut last = 0.0f64; + Some( + samples + .into_iter() + .map(|(x, y)| { + last = x.clamp(last, 1.0); + (last, y.clamp(0.0, 1.0)) + }) + .collect(), + ) +} + +/// The parameters strictly between 0 and 1 where the cubic Bézier with control values `a`, `b`, +/// `c` and `d` stops rising or falling (where its derivative is 0). The values are scaled into +/// -1..1 first, so huge ones can't overflow the discriminant. +fn turning_points(a: f64, b: f64, c: f64, d: f64) -> [Option; 2] { + let scale = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); + if !(scale.is_finite() && scale > 0.0) { + return [None, None]; + } + let (a, b, c, d) = (a / scale, b / scale, c / scale, d / scale); + let (d0, d1, d2) = (b - a, c - b, d - c); + let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); + let inside = |t: f64| (t.is_finite() && t > 0.0 && t < 1.0).then_some(t); + if qa.abs() < 1e-12 { + return [if qb.abs() < 1e-12 { None } else { inside(-qc / qb) }, None]; + } + let disc = qb * qb - 4.0 * qa * qc; + if disc < 0.0 { + return [None, None]; + } + let root = disc.sqrt(); + [inside((-qb - root) / (2.0 * qa)), inside((-qb + root) / (2.0 * qa))] +} + struct Anchor { p: Point, inh: Option, @@ -260,3 +342,19 @@ fn corner_radii(fields: Vec<&Value>) -> Option> { .collect(), ) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn turning_points_of_huge_control_values_are_found() { + let small = turning_points(1.0, -3.0, 3.0, 1.0); + let huge = turning_points(1e200, -3e200, 3e200, 1e200); + assert!(small.iter().all(Option::is_some), "{small:?}"); + for (s, h) in small.iter().zip(&huge) { + let (Some(s), Some(h)) = (s, h) else { panic!("{huge:?}") }; + assert!((s - h).abs() < 1e-12, "{small:?} {huge:?}"); + } + } +} diff --git a/crates/affinity/src/model/read.rs b/crates/affinity/src/model/read.rs index daf5d778c6..00910baabd 100644 --- a/crates/affinity/src/model/read.rs +++ b/crates/affinity/src/model/read.rs @@ -26,6 +26,9 @@ const MAX_DOCUMENT_CHARS: usize = 16 << 20; /// Table cells of all tables together (each becomes a text object with its edge lines). const MAX_DOCUMENT_CELLS: usize = 1 << 18; +/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers). +const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20; + /// What a whole read may still use. Shared objects can be linked from many layers, and embedded /// documents are read with what their embedding document left, so linking or embedding the /// same content many times can't multiply the work. @@ -39,10 +42,18 @@ pub(crate) struct Budget { pub(crate) chars: usize, /// Table cells ([`MAX_DOCUMENT_CELLS`] in all). pub(crate) cells: usize, + /// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all). + pub(crate) pressure: usize, } impl Budget { - pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS }; + pub(crate) const FULL: Budget = Budget { + nodes: MAX_NODES, + pixels: MAX_LAYER_PIXELS, + chars: MAX_DOCUMENT_CHARS, + cells: MAX_DOCUMENT_CELLS, + pressure: MAX_DOCUMENT_PRESSURE_POINTS, + }; } /// Read a document: archive, `doc.dat` and the model. @@ -441,8 +452,34 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { _ => self.warn("layer effects of other kinds (left out)"), } } + for a in s.objs(id, b"AdCh") { + if let Some(effect) = self.attached_recolor(a) { + out.push(effect); + } + } out } + fn attached_recolor(&mut self, a: ObjId) -> Option { + let s = self.s; + if !s.is(a, b"RcRA") { + return None; + } + if s.bool(a, b"Visi") == Some(false) { + return None; + } + let adjp = s.obj(a, b"AdjP")?; + if !s.is(adjp, b"RecP") { + return None; + } + let h = s.f64(adjp, b"RecH").unwrap_or(0.0); + let sat = s.f64(adjp, b"RecS").unwrap_or(1.0); + let l = s.f64(adjp, b"RecL").unwrap_or(0.5); + let (r, g, b) = crate::paint::hsl(h, sat, l); + let color = crate::paint::Color::Rgb { r, g, b, a: 1.0 }; + let opacity = s.f64(a, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); + let blend = self.effect_blend(a); + Some(Effect::ColorOverlay { color, opacity, blend }) + } /// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned). fn effect_blend(&mut self, e: ObjId) -> Blend { @@ -479,6 +516,8 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { Some(_) => self.warn("several pixel masks on one layer (only the first is used)"), None => {} } + } else if class == Tag::of(b"RcRA") { + // Handled in `effects` as a colour overlay. } else { self.warn(format!("{} layers attached to other layers (imported without them)", describe(class))); } diff --git a/crates/affinity/src/paint.rs b/crates/affinity/src/paint.rs index 8f9e424aae..12102581e1 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -121,6 +121,9 @@ pub struct Stroke { pub dash: Option<(Vec, f64)>, /// Painted below the fill instead of above it. pub behind: bool, + /// The pressure curve: (position 0..1 along the path, width as a fraction of `width`) in + /// order along the path, `None` for a stroke of the same width all along. + pub profile: Option>, } /// Gradient stops per gradient. @@ -194,7 +197,7 @@ fn color_within(r: &mut Reader, id: ObjId, depth: u32) -> Option { }) } -fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) { +pub(crate) fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) { let c = (1.0 - (2.0 * l - 1.0).abs()) * s; let hp = (h.rem_euclid(1.0)) * 6.0; let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); @@ -350,8 +353,50 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh } _ => None, }; - if s.obj(lsty, b"Brus").is_some() || s.obj(ldsc, b"LDeP").is_some() { - r.warn("brush and pressure strokes (imported as plain strokes)"); + if s.obj(lsty, b"Brus").is_some() { + r.warn("brush strokes (imported as plain strokes)"); + } + // The pressure curve sets the width along the path; one at full width all along is a plain + // stroke. Every curve read counts against the document's points: one at full width counts its + // points, and one that can't be read counts the most a curve may have. Once the points are + // used up the rest are not read. + const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)"; + let ldep = s.obj(ldsc, b"LDeP"); + if ldep.is_some() && r.budget.pressure == 0 { + r.warn(BEYOND); + } + let profile = match ldep.filter(|_| r.budget.pressure > 0).map(|p| crate::geometry::pressure(r, p)) { + Some(Some(points)) => match r.budget.pressure.checked_sub(points.len()) { + Some(left) => { + r.budget.pressure = left; + (!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-9)).then_some(points) + } + None => { + r.budget.pressure = 0; + r.warn(BEYOND); + None + } + }, + Some(None) => { + r.budget.pressure = r.budget.pressure.saturating_sub(crate::geometry::MAX_PRESSURE_CURVE_POINTS); + r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)"); + None + } + None => None, + }; + Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind, profile }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hsl_lightness_1_is_white_and_0_is_black() { + assert_eq!(hsl(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)); + assert_eq!(hsl(0.5, 1.0, 1.0), (1.0, 1.0, 1.0)); + assert_eq!(hsl(0.0, 1.0, 0.0), (0.0, 0.0, 0.0)); + let (r, g, b) = hsl(0.0, 1.0, 0.5); + assert!((r - 1.0).abs() < 1e-6 && g.abs() < 1e-6 && b.abs() < 1e-6); } - Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind }) } diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 779a58552e..13e8f0c53a 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -1,7 +1,7 @@ -affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=d23a6900;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)", "brush and pressure strokes (imported as plain strokes) (114×)"] -affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=b8cecb1c;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)", "brush and pressure strokes (imported as plain strokes) (534×)"] -affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=23d1e39c;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)", "brush and pressure strokes (imported as plain strokes) (54×)"] -affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=cafb7572;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush and pressure strokes (imported as plain strokes)"] +affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] +affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] +affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] +affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] @@ -30,4 +30,4 @@ patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"] patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] -patchy-vector.af dpi=72;spreads=1;model_crc32=b36a9767;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] +patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] diff --git a/crates/affinity/tests/support/text_fixture.rs b/crates/affinity/tests/support/text_fixture.rs index 574a0ca38a..01baa067e8 100644 --- a/crates/affinity/tests/support/text_fixture.rs +++ b/crates/affinity/tests/support/text_fixture.rs @@ -98,20 +98,26 @@ pub fn utf8(text: &str) -> F { } pub fn document(blocks: Vec, frame: bool, dpi: f64, transform: [f64; 6]) -> Vec { - let text = F::Obj( - tag(if frame { b"TxtF" } else { b"TxtA" }), - vec![ - (tag(b"StSt"), F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(blocks))])), - ( - tag(b"TxtH"), - F::Obj( - tag(if frame { b"FrFr" } else { b"ArFr" }), - vec![(tag(b"FrmB"), F::F64s(vec![10.0, 20.0, 210.0, 120.0])), (tag(b"ArtV"), F::F64(18.0))], - ), + document_with_children(blocks, frame, dpi, transform, vec![]) +} + +/// [`document`] whose text holds `children` (objects nested inside the text). +pub fn document_with_children(blocks: Vec, frame: bool, dpi: f64, transform: [f64; 6], children: Vec) -> Vec { + let mut fields = vec![ + (tag(b"StSt"), F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(blocks))])), + ( + tag(b"TxtH"), + F::Obj( + tag(if frame { b"FrFr" } else { b"ArFr" }), + vec![(tag(b"FrmB"), F::F64s(vec![10.0, 20.0, 210.0, 120.0])), (tag(b"ArtV"), F::F64(18.0))], ), - (tag(b"Xfrm"), F::F64s(transform.to_vec())), - ], - ); + ), + (tag(b"Xfrm"), F::F64s(transform.to_vec())), + ]; + if !children.is_empty() { + fields.push((tag(b"Chld"), F::Shared(children))); + } + let text = F::Obj(tag(if frame { b"TxtF" } else { b"TxtA" }), fields); let mut root = vec![ (tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(dpi))])), ( diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 9ef049f860..179c0de516 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -138,9 +138,10 @@ pub fn stain(inst: &Node) -> Option<(Color, f32)> { Some((f.paint.color()?, f.opacity)) } -/// A symbol's art for instance `inst`, stained by the instance's fill ([`stain`]). +/// A symbol's art for instance `inst`: with the instance's own appearance changes to it (a dynamic +/// symbol's, [`vectorcraft_doc::symbol_overrides`]), stained by the instance's fill ([`stain`]). pub fn instance_art(art: &Node, inst: &Node) -> Node { - let mut a = art.clone(); + let mut a = vectorcraft_doc::symbol_overrides::dynamic_art(art, inst); if let Some((c, amount)) = stain(inst) { tint_node(&mut a, &c, amount); } diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index e76e67ba5b..fbec570112 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -386,10 +386,22 @@ impl CornerSource { #[serde(default)] pub struct PatternBrush { pub side: Node, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub side_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub outer_corner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub outer_corner_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub inner_corner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inner_corner_swatch: Option, /// What the outer corners take when there is no `outer_corner` art. Without art or a source, /// they take the `inner_corner` art. #[serde(skip_serializing_if = "Option::is_none")] @@ -400,8 +412,16 @@ pub struct PatternBrush { pub inner_source: Option, #[serde(skip_serializing_if = "Option::is_none")] pub start: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_swatch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub end: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_frame: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_swatch: Option, /// Scale in percent. pub scale: f64, /// Space between tiles in percent of the tile width. @@ -422,12 +442,22 @@ impl Default for PatternBrush { fn default() -> Self { Self { side: defaults::stitch_tile(), + side_frame: None, + side_swatch: None, outer_corner: None, + outer_corner_frame: None, + outer_corner_swatch: None, inner_corner: None, + inner_corner_frame: None, + inner_corner_swatch: None, outer_source: None, inner_source: None, start: None, + start_frame: None, + start_swatch: None, end: None, + end_frame: None, + end_swatch: None, scale: 100.0, spacing: 0.0, fit: PatternFit::Stretch, @@ -500,6 +530,14 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn valid_tile_frame(frame: Rect) -> bool { + [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) + && frame.width().is_finite() + && frame.height().is_finite() + && frame.width() > 1e-9 + && frame.height() > 1e-9 +} + impl Colorization { /// A Hue Shift key colour that isn't a colour (components out of reach) becomes black. fn sanitize(&mut self) { @@ -600,6 +638,11 @@ impl Brush { BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); + for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { + if frame.is_some_and(|f| !valid_tile_frame(f)) { + *frame = None; + } + } p.colorization.sanitize(); } BrushKind::Bristle(b) => { diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 884dd27cf2..a7320895ce 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -27,10 +27,16 @@ fn near(a: f64, b: f64, tol: f64) -> bool { (a - b).abs() <= tol } +/// Points along every outline under `n`, its anchors among them. Bent art keeps its curves and +/// long lines since #3926, so its anchors alone no longer trace it. fn all_points(n: &Node, out: &mut Vec) { n.walk(&mut |c| { - if let Some(p) = c.path_data() { - out.extend(p.anchors().map(|(_, _, a)| a.p)); + for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) { + out.extend(sp.anchors.iter().map(|a| a.p)); + for i in 0..sp.segment_count() { + let seg = sp.segment(i); + out.extend((1..32).map(|j| kurbo::ParamCurve::eval(&seg, j as f64 / 32.0))); + } } }); } @@ -185,9 +191,12 @@ fn art_brush_follows_curves() { } } let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(10.0, 4.0), ArtScale::Stretch), &bp_open, &stroke(1.0)); + // The long edges bend as curves (#3926), where they used to be cut into some 400 chords. The + // path is run along in 0.05 pt chords, which the curves follow, so a few dozen remain. + let (anchors, curved) = anchors_and_curved(&out[0]); + assert!(anchors < 100 && curved > anchors / 2, "long edges bend as curves: {curved} of {anchors} anchors with handles"); let mut pts = vec![]; all_points(&out[0], &mut pts); - assert!(pts.len() > 40, "long edges are subdivided so they bend: {}", pts.len()); for p in pts { let r = p.distance(Point::new(100.0, 100.0)); assert!((r - 100.0).abs() <= 2.0 + 0.3, "point {p:?} is {r} from the centre"); @@ -552,6 +561,43 @@ fn pattern_corner_source_none_leaves_that_kind_of_corner_empty() { assert!((outer == plain && inner == saved) || (inner == plain && outer == saved), "only the corners set to None are empty"); } +#[test] +fn pattern_without_start_tile_runs_side_to_path_start() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = Some(rect_art(20.0, 4.0)); + } + let with_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(with_start[0].geometric_bounds().unwrap().width(), 20.0); + if let BrushKind::Pattern(p) = &mut b.kind { + p.start = None; + } + let without_start = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_start.len(), 10); + assert!(near(without_start[0].geometric_bounds().unwrap().x0, 0.0, 1e-6)); + assert!(near(without_start[0].geometric_bounds().unwrap().width(), 10.0, 1e-6)); +} + +#[test] +fn pattern_without_end_tile_runs_side_to_path_end() { + let path = line(0.0, 0.0, 100.0, 0.0); + let doc = Document::new(1.0, 1.0); + let mut b = pattern_brush(PatternFit::Stretch, false); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = Some(rect_art(20.0, 4.0)); + } + let with_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert!(with_end.iter().any(|n| near(n.geometric_bounds().unwrap().width(), 20.0, 1e-6))); + if let BrushKind::Pattern(p) = &mut b.kind { + p.end = None; + } + let without_end = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(without_end.len(), 10); + assert!(near(without_end.last().unwrap().geometric_bounds().unwrap().x1, 100.0, 1e-6)); +} + #[test] fn pattern_corner_sources_round_trip_and_stay_out_of_brushes_without_them() { let saved = serde_json::to_value(pattern_brush(PatternFit::Stretch, true)).unwrap(); @@ -1088,7 +1134,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { let mut brushed = rect_art(10.0, 4.0); brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) })); for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed)] { - doc.symbols.push(Symbol { name: name.into(), art: std::sync::Arc::new(art.clone()) }); + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art.clone()) }); doc.patterns.push(PatternDef::new(name, vec![std::sync::Arc::new(art)])); } let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); @@ -1226,11 +1272,12 @@ fn a_pattern_tile_keeps_its_curves_on_a_straight_path() { assert!(near(b.height(), 40.0, 1.0), "and still stand the tile's height: {}", b.height()); } -/// The other half of the same behaviour: where the path really does bend, the tile is still -/// subdivided, because an affine cannot reproduce a bend. The fit is checked before it is used, -/// so a bent run falls back to exactly what it did before. +/// The other half of the same behaviour: where the path really does bend, an affine cannot +/// reproduce the bend, so the tile is bent, and it still comes out as curves: cubics fitted to the +/// bent art rather than the chords it used to be flattened into (#3926). Here a 4-anchor circle +/// tile runs round a circle of radius 200, so its outline stays in the band 20 either side of it. #[test] -fn a_pattern_tile_on_a_bent_path_is_still_subdivided() { +fn a_pattern_tile_on_a_bent_path_keeps_its_curves() { let circle = Node::path(NodeId(0), shapes::ellipse(Rect::new(0.0, -20.0, 40.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); let brush = Brush { @@ -1240,9 +1287,23 @@ fn a_pattern_tile_on_a_bent_path_is_still_subdivided() { // A circle to run along: every tile sits on a curving section. let round = shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath(); let out = stroke_pieces(&Document::new(1.0, 1.0), &brush, &round, &stroke(1.0)); - assert!(!out.is_empty()); - let bent = out.iter().filter(|n| anchors_and_curved(n).0 > 8).count(); - assert!(bent > out.len() / 2, "tiles on a bend are still densified: {bent} of {}", out.len()); + assert!(out.len() > 20, "tiles all the way round: {}", out.len()); + let (mut lo, mut hi) = (f64::MAX, f64::MIN); + for n in &out { + let (anchors, curved) = anchors_and_curved(n); + assert!((4..=16).contains(&anchors), "a bent circle tile is a few curves, not a polygon: {anchors} anchors"); + assert!(curved == anchors, "every anchor keeps a handle: {curved} of {anchors}"); + let mut pts = vec![]; + all_points(n, &mut pts); + for q in pts { + let r = q.distance(Point::new(200.0, 200.0)); + (lo, hi) = (lo.min(r), hi.max(r)); + } + } + // The path is a cubic circle (0.06 out at most) run along in chords of 0.05, and the fit holds + // a quarter of the 0.25 flattening tolerance, so the band holds to 0.2. + assert!(lo > 179.8 && hi < 220.2, "the curves stay in the tile's band round the path: {lo:.3}..{hi:.3}"); + assert!(lo < 180.2 && hi > 219.8, "and reach both edges of it: {lo:.3}..{hi:.3}"); } /// The kind of every node in a piece of brushed art, in paint order. diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 95632ad495..78c2f547f3 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -1,13 +1,15 @@ //! Art, scatter and pattern brushes: art bent along the path by arc length. //! //! Art coordinates `(x, y)` map to the path point at arc length `s(x)` offset by -//! `(y - centre) × cross` along the path's left normal. Art outlines are flattened and -//! subdivided first so long straight edges bend with the path instead of cutting chords. +//! `(y - centre) × cross` along the path's left normal. Art outlines come out as cubics fitted +//! to the bent art, so curves stay curves and long straight edges bend with the path (#3926); +//! where that would take more anchors than chords, they are flattened and subdivided instead. use std::sync::Arc; +use kurbo::ParamCurveNearest; use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile}; -use vectorcraft_geom::{Affine, BezPath, PathData, PathEl, Point, Rect, SubPath, Vec2}; +use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2}; use crate::track::{Rng, Track, normal, seed_of, tracks}; use crate::{ArtBrush, ArtScale, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation, tolerance}; @@ -34,22 +36,27 @@ const MAX_WALK: usize = 10_000; /// Points on each side of the box an Auto-Sliced pattern brush corner masks its tiles with. const MASK_STEPS: usize = 32; -/// Bend every path under `n` through `f`. Paths are flattened with `flat_tol` (art space) and -/// segments subdivided so none is longer than `max_du` along x. Stroke widths scale by -/// `width_scale`. Text, images and symbol instances can't bend and are dropped. -pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, width_scale: f64) -> Option { +/// Bend every path under `n` through `f`. Each art segment comes out as cubics that follow it +/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document +/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than +/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord +/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`. +/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask +/// bends with the object it masks. +pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option { let mut out = n.clone(); out.appearance.scale_strokes(width_scale); match &mut out.kind { NodeKind::Path { path, live, .. } => { *live = None; - *path = warp_path(path, f, flat_tol, max_du); + *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol)); if path.is_empty() { return None; } } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => { - let kids: Vec> = children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, width_scale)).map(Arc::new).collect(); + let kids: Vec> = + children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect(); if kids.is_empty() { return None; } @@ -57,57 +64,171 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max } _ => return None, } + map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale)); Some(out) } -fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64) -> PathData { - let bp = p.to_bezpath(); +/// Replace the art of `n`'s linked opacity mask, if it has one, with what `map` makes of it. Where +/// `map` draws nothing, the mask's art becomes an empty group. +fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option) { + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && m.linked + { + let id = m.art.id; + m.art = Arc::new(map(&m.art).unwrap_or_else(|| Node::group(id, vec![]))); + } +} + +/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords +/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords. +fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData { let mut subs = vec![]; - let mut cur: Vec = vec![]; - let mut els = vec![]; - kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| els.push(e)); - let finish = |cur: &mut Vec, closed: bool, subs: &mut Vec| { - let pts = std::mem::take(cur); - if pts.len() < 2 { - return; + for sp in &p.subpaths { + let Some(dense) = densified(sp, flat_tol, max_du) else { continue }; + if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) { + subs.push(fit); + continue; } - let mut dense = vec![pts[0]]; - let n = pts.len(); - let segs = if closed { n } else { n - 1 }; - for i in 0..segs { - let (a, b) = (pts[i], pts[(i + 1) % n]); - let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB); - for j in 1..=k { - let q = a.lerp(b, j as f64 / k as f64); - if closed && i == segs - 1 && j == k { - break; - } - dense.push(q); - } - } - let mapped: Vec = dense.into_iter().map(f).collect(); - subs.push(SubPath::polyline(&mapped, closed)); - }; - for e in els { - match e { - PathEl::MoveTo(q) => { - finish(&mut cur, false, &mut subs); - cur.push(q); - } - PathEl::LineTo(q) => cur.push(q), - PathEl::ClosePath => { - if cur.len() > 1 && cur[0].distance(cur[cur.len() - 1]) < 1e-9 { - cur.pop(); - } - finish(&mut cur, true, &mut subs); - } - _ => {} + let mapped: Vec = dense.into_iter().map(f).filter(|q| q.is_finite()).collect(); + if mapped.len() >= 2 { + subs.push(SubPath::polyline(&mapped, sp.closed)); } } - finish(&mut cur, false, &mut subs); PathData::new(subs) } +/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along +/// x, in art space: the points the chord route maps. `None` below two points. +fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { + let mut bp = BezPath::new(); + sp.to_bezpath_into(&mut bp); + let mut pts = vec![]; + kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| { + if let PathEl::MoveTo(q) | PathEl::LineTo(q) = e { + pts.push(q); + } + }); + if sp.closed && pts.len() > 1 && pts.first()?.distance(*pts.last()?) < 1e-9 { + pts.pop(); + } + if pts.len() < 2 { + return None; + } + let segs = if sp.closed { pts.len() } else { pts.len() - 1 }; + let mut dense = vec![*pts.first()?]; + for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() { + let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB); + for j in 1..=k { + if sp.closed && i == segs - 1 && j == k { + break; + } + dense.push(a.lerp(b, j as f64 / k as f64)); + } + } + Some(dense) +} + +/// Times an art segment is halved at most while looking for cubics that fit it. +const FIT_DEPTH: u32 = 12; +/// Parameter step of the finite differences that stand in for the bend's derivative. +const FIT_DT: f64 = 1e-6; +/// Sections a fitted piece is checked at the ends of (the ends themselves are exact). +const FIT_CHECKS: usize = 8; +/// Share of the flattening tolerance the fitted curves hold to. The chords were exact at their +/// points and a few hundredths off between them, so a straight edge bends about as closely. +const FIT_SHARE: f64 = 0.25; +/// Tolerance paths are flattened to before art is laid along them. +const TRACK_TOL: f64 = 0.05; + +/// The distance (document space) fitted curves keep to the bent art, for flattening tolerance +/// `doc_tol`: never below [`TRACK_TOL`], since following the flattened path more closely than it +/// follows the real one only traces its chords. +fn fit_tol(doc_tol: f64) -> f64 { + (doc_tol * FIT_SHARE).max(TRACK_TOL) +} + +/// `sp` through `f` as cubics within `tol` (document space), one or more per art segment so its +/// anchors, corners included, stay anchors. `None` when that takes more than `most` anchors, when +/// a piece still does not fit after [`FIT_DEPTH`] halvings, or when `f` cannot place a point. +/// +/// Each piece is the cubic with the bent piece's ends and their derivatives, which is the piece +/// itself where the bend is affine and converges fast where it is not. It is checked against the +/// bend at the same parameters, so the distance measured is never less than the true one. The +/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out +/// on a map that never fits; the depth and the anchor count bound this one. +fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option { + if !(tol.is_finite() && tol > 0.0) { + return None; + } + let start = f(sp.anchors.first()?.p); + if !start.is_finite() { + return None; + } + let mut bp = BezPath::new(); + bp.move_to(start); + // Pieces allowed: an open subpath's first anchor is one more, a closed one's last piece ends on it. + let mut room = if sp.closed { most } else { most.checked_sub(1)? }; + for i in 0..sp.segment_count() { + let c = sp.segment(i); + let line = sp.segment_is_line(i); + // A line's handles sit on its ends, which stalls its parameter there; thirds keep it even. + let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c }; + let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite()); + fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + } + if sp.closed { + bp.close_path(); + } + // The last piece ends on the first anchor's image, so a closed subpath merges it back in; the + // count is checked again for a map that jumps right there and keeps the two apart. + PathData::from_bezpath(&bp).subpaths.into_iter().next().filter(|s| s.anchors.len() <= most) +} + +/// Pieces for parameters `t0..t1` of the bent segment `at` onto `bp`, which ends at `at(t0)`: +/// halved until each is within `tol`, at most `depth` times and `room` pieces. A `line` that is +/// still straight within `tol` stays a line. +fn fit_into( + at: &dyn Fn(f64) -> Option, + (t0, t1): (f64, f64), + line: bool, + tol: f64, + depth: u32, + bp: &mut BezPath, + room: &mut usize, +) -> Option<()> { + let span = t1 - t0; + let (p0, p3) = (at(t0)?, at(t1)?); + // Derivatives read from inside the piece, so a kink at either end (a corner, a turn of the + // track) stays one. + let d0 = (at(t0 + FIT_DT)? - p0) * (span / FIT_DT); + let d1 = (p3 - at(t1 - FIT_DT)?) * (span / FIT_DT); + let c = CubicBez::new(p0, p0 + d0 / 3.0, p3 - d1 / 3.0, p3); + let chord = kurbo::Line::new(p0, p3); + let (mut curve_fits, mut line_fits) = (c.is_finite(), line); + for k in 1..FIT_CHECKS { + if !(curve_fits || line_fits) { + break; + } + let u = k as f64 / FIT_CHECKS as f64; + let q = at(t0 + span * u)?; + curve_fits &= q.distance(c.eval(u)) <= tol; + line_fits &= chord.nearest(q, 1e-9).distance_sq <= tol * tol; + } + if line_fits || curve_fits { + *room = room.checked_sub(1)?; + if line_fits { + bp.line_to(p3); + } else { + bp.curve_to(c.p1, c.p2, p3); + } + return Some(()); + } + let depth = depth.checked_sub(1)?; + let mid = t0 + span / 2.0; + fit_into(at, (t0, mid), line, tol, depth, bp, room)?; + fit_into(at, (mid, t1), line, tol, depth, bp, room) +} + /// Art turned so it runs left → right, flipped as requested; returns it with its bounds. fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> { let mut a = art.clone(); @@ -126,6 +247,16 @@ fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) -> (b.width() > 1e-9).then_some((a, b)) } +/// Orient a tile's repeat frame with its art. The frame can be smaller than the art. +fn oriented_tile(art: &Node, frame: Option, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> { + let (node, bounds) = oriented(art, Direction::LeftToRight, flip_along, flip_across)?; + let Some(frame) = frame else { return Some((node, bounds)) }; + let x = if flip_along { (-frame.x1, -frame.x0) } else { (frame.x0, frame.x1) }; + let y = if flip_across { (-frame.y1, -frame.y0) } else { (frame.y0, frame.y1) }; + let frame = Rect::new(x.0, y.0, x.1, y.1); + (frame.width() > 1e-9 && frame.height() > 1e-9).then_some((node, frame)) +} + /// Piecewise-linear map from art x (offset from the art's left edge) to arc length. #[derive(Clone, Copy, Debug)] pub(crate) struct AlongMap { @@ -230,7 +361,8 @@ fn affine_fit(f: &dyn Fn(Point) -> Point, b: Rect, tol: f64) -> Option { /// Everything else matches [`warp_node`] deliberately, so curves are the only difference between /// the two routes: the same node kinds are kept and the rest dropped, `live` is cleared on every /// path, an empty path or a group left with no children is dropped, and strokes are scaled by -/// `width_scale` at every level rather than by the transform's own factor. +/// `width_scale` at every level rather than by the transform's own factor, the art of linked +/// opacity masks included. fn affine_node(n: &Node, a: Affine, width_scale: f64) -> Option { let mut out = prepared(n, width_scale)?; out.transform(a, false); @@ -257,6 +389,7 @@ fn prepared(n: &Node, width_scale: f64) -> Option { } _ => return None, } + map_mask(&mut out, |art| prepared(art, width_scale)); Some(out) } @@ -281,7 +414,7 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option f64) -> Node { if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } = &mut out.kind { *children = children.iter().map(|c| Arc::new(widen_strokes(c, factor))).collect(); } + map_mask(&mut out, |art| Some(widen_strokes(art, factor))); out } @@ -377,7 +511,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre let width = light.max(heavy); let cross = weight * width / 100.0; let mut out = vec![]; - for t in tracks(bp, 0.05) { + for t in tracks(bp, TRACK_TOL) { let l = t.len(); if l <= 1e-9 { continue; @@ -419,7 +553,7 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option< let mut rng = Rng::new(seed_of(bp, name)); let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes(); let mut out = Budget::default(); - for t in tracks(bp, 0.05) { + for t in tracks(bp, TRACK_TOL) { if out.full() { break; } @@ -482,6 +616,9 @@ fn anchors_of(n: &Node) -> usize { if let Some(c) = n.children() { stack.extend(c.iter().map(Arc::as_ref)); } + if let Some(m) = &n.extras().mask { + stack.push(&m.art); + } } total } @@ -588,7 +725,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k } let s = if tw > 1e-9 { len / tw } else { 1.0 }; let max_du = MAX_SEG / (2.0 * k * s.max(1.0)); - let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, k); + let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k); // Art point → (distance along from the left edge, stretched to `len`, and offset across). let along = move |q: Point| { let (x, y) = local(q); @@ -673,20 +810,20 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option { } pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { - let orient = |n: &Node| oriented(n, Direction::LeftToRight, pb.flip_along, pb.flip_across); - let Some(side) = orient(&pb.side) else { return vec![] }; + let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); + let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; let k = weight * pb.scale.max(1.0) / 100.0; - let outer = pb.outer_corner.as_ref().and_then(orient); - let inner = pb.inner_corner.as_ref().and_then(orient); - let start = pb.start.as_ref().and_then(orient); - let end = pb.end.as_ref().and_then(orient); + let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); + let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); + let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); + let end = pb.end.as_ref().and_then(|n| orient(n, pb.end_frame)); let tw = side.1.width() * k; let gap = tw * pb.spacing.max(0.0) / 100.0; // Each kind of corner takes its own art, else its source, else the other kind's art. let outer_tile = outer.as_ref().map(Corner::Art).or(pb.outer_source.map(Corner::Source)); let inner_tile = inner.as_ref().map(Corner::Art).or(pb.inner_source.map(Corner::Source)); let mut out = Budget::default(); - for t in tracks(bp, 0.05) { + for t in tracks(bp, TRACK_TOL) { if out.full() { break; } @@ -921,4 +1058,156 @@ mod tests { let moved = bend(&straight, &circle, b, along, cross).expect("the straight run still draws something"); assert_eq!(anchors(&moved), 4, "the straight run keeps the tile's curves"); } + + /// A 4-anchor circle tile filling `b`. + fn circle_tile(b: Rect) -> Node { + Node::path( + NodeId(0), + vectorcraft_geom::shapes::ellipse(b), + Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ) + } + + /// `per` points along each segment of `sp`, through `f`. + fn traced(sp: &SubPath, f: &dyn Fn(Point) -> Point, per: usize) -> Vec { + (0..sp.segment_count()) + .flat_map(|i| { + let c = sp.segment(i); + (0..per).map(move |j| f(c.eval(j as f64 / per as f64))) + }) + .collect() + } + + /// How far apart two closed outlines get (Hausdorff distance, each taken as a polygon). + fn apart(a: &[Point], b: &[Point]) -> f64 { + let to = |q: Point, pts: &[Point]| { + pts.iter() + .zip(pts.iter().cycle().skip(1)) + .map(|(&a, &b)| { + let ab = b - a; + let t = ((q - a).dot(ab) / ab.hypot2().max(1e-18)).clamp(0.0, 1.0); + q.distance(a + ab * t) + }) + .fold(f64::MAX, f64::min) + }; + let one_way = |a: &[Point], b: &[Point]| a.iter().map(|&q| to(q, b)).fold(0.0, f64::max); + one_way(a, b).max(one_way(b, a)) + } + + /// #3926: on a bend the tile is fitted with cubics instead of flattened into chords. A circle + /// tile bent round a circle stays a handful of smooth curves, closer to the bent art than the + /// chords were, in a small fraction of their anchors. + #[test] + fn a_circle_tile_bent_round_a_circle_stays_a_few_curves() { + let round = vectorcraft_geom::shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath(); + let t = tracks(&round, 0.05).remove(0); + let b = Rect::new(0.0, -20.0, 40.0, 20.0); + let along = AlongMap::linear(b.width(), 100.0, 140.0); + let tile = circle_tile(b); + let NodeKind::Path { path: art, .. } = &tile.kind else { panic!("the tile is a path") }; + let art = &art.subpaths[0]; + + let bent = bend(&t, &tile, b, along, 1.0).expect("the tile is drawn"); + let NodeKind::Path { path, .. } = &bent.kind else { panic!("a bent path is a path") }; + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(sp.closed, "still a closed outline"); + let n = sp.anchors.len(); + assert!((4..=16).contains(&n), "a few anchors, the tile's own four among them: {n}"); + assert!(sp.anchors.iter().all(|a| a.has_in() && a.has_out()), "every anchor keeps both handles"); + assert!(sp.anchors.first().map(|a| a.p) != sp.anchors.last().map(|a| a.p), "closed without a duplicate anchor"); + + // The same map `bend` uses, at scale 1, and the tolerance it fits to. + let (cy, x0) = (b.center().y, b.x0); + let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy); + let tol = tolerance(b.height().max(b.width())); + let exact = traced(art, &f, 1000); + let chords: Vec = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect(); + let curves = traced(sp, &|p| p, 200); + let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact)); + // Checked at eight points a piece, so a little room between them. + assert!(e_curves <= fit_tol(tol) * 1.5, "the curves follow the bent art within {}: {e_curves:.4}", fit_tol(tol)); + assert!(e_curves < e_chords, "closer than the chords were: {e_curves:.4} against {e_chords:.4}"); + assert!(chords.len() >= 4 * n, "far fewer anchors than the {} chords took: {n}", chords.len()); + } + + /// Fitting is bounded however badly the map behaves: where it gives points that are not finite + /// the tile falls back to chords with those points left out (or to nothing), and where it never + /// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either + /// way the call comes back promptly with finite geometry. + #[test] + fn a_map_that_misbehaves_still_returns_promptly_and_finite() { + let b = Rect::new(0.0, -20.0, 40.0, 20.0); + let tile = circle_tile(b); + let finite = |n: &Node| match &n.kind { + NodeKind::Path { path, .. } => { + path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) + } + _ => false, + }; + let maps: [&dyn Fn(Point) -> Point; 4] = [ + &|p| if p.x > 25.0 { Point::new(f64::NAN, p.y) } else { p }, + &|p| if p.y > 10.0 { Point::new(f64::INFINITY, p.y) } else { p + Vec2::new(p.x.sin(), 0.0) }, + &|p| Point::new(p.x, p.y + if (p.x * 1e3).sin() > 0.0 { 5.0 } else { 0.0 }), + &|_| Point::new(f64::NAN, f64::NAN), + ]; + for (i, f) in maps.iter().enumerate() { + let t0 = std::time::Instant::now(); + let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0); + assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed()); + match (i, &out) { + (3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"), + (_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"), + (_, None) => panic!("map {i} places most points, so something is drawn"), + } + } + } + + /// A linked opacity mask on brush art bends and widens with the art, on a bent run and on a + /// straight one, so a mask drawn over the art still covers it. An unlinked mask stays put. + #[test] + fn a_linked_opacity_mask_bends_with_the_art() { + let b = Rect::new(0.0, -20.0, 40.0, 20.0); + let stroked = |id: u64| { + Node::path( + NodeId(id), + vectorcraft_geom::shapes::ellipse(b), + Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + 2.0, + ), + ) + }; + let masked = |linked: bool| { + let mut n = stroked(0); + let mut mask = vectorcraft_doc::OpacityMask::new(stroked(1), true); + mask.linked = linked; + n.extras_mut().mask = Some(Box::new(mask)); + n + }; + let round = vectorcraft_geom::shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath(); + let bent_track = tracks(&round, 0.05).remove(0); + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((320.0, 0.0)); + let straight_track = tracks(&line, 0.01).remove(0); + let along = AlongMap::linear(b.width(), 100.0, 140.0); + for (name, t) in [("bent", &bent_track), ("straight", &straight_track)] { + let out = bend(t, &masked(true), b, along, 2.0).expect("the art is drawn"); + let mask = out.extras().mask.as_ref().expect("the mask is kept"); + assert_eq!(mask.art.kind, out.kind, "{name} run: the mask's art bends with the art it was drawn over"); + assert_eq!(mask.art.appearance, out.appearance, "{name} run: the mask's strokes widen with the art's"); + + let out = bend(t, &masked(false), b, along, 2.0).expect("the art is drawn"); + let mask = out.extras().mask.as_ref().expect("the mask is kept"); + assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was"); + + let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn"); + let mask = out.extras().mask.as_ref().expect("the mask is kept"); + assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art"); + assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's"); + } + assert_eq!(anchors_of(&masked(true)), 8, "the anchor budget counts the mask's art"); + } } diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index 4886d9ea5b..2ea6dea4fb 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -21,5 +21,6 @@ image = { workspace = true } [dev-dependencies] serde_json = { workspace = true } -# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). -vectorcraft-text = { workspace = true, features = ["bundled-fonts"] } +# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine) +# and in fonts built in code (`vectorcraft_text::test_fonts`). +vectorcraft-text = { workspace = true, features = ["bundled-fonts", "test-fonts"] } diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 1e43c45dc2..6857c2a175 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -622,7 +622,7 @@ impl<'d, 'a> Build<'d, 'a> { let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); self.symbol_names.insert(symbol.clone()); - self.doc.symbols.push(Symbol { name: symbol.clone(), art: Arc::new(art) }); + self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) }); symbol }); self.symbols.insert(key, made.clone()); diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index d0dde65c90..6bd3d1c106 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -1049,6 +1049,34 @@ fn drawings_the_export_writes_read_back() { } } +#[test] +fn a_lone_segment_reads_back_from_the_line_the_export_writes() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut b = kurbo::BezPath::new(); + b.move_to((20.0, 30.0)); + b.line_to((120.0, 70.0)); + let id = doc.alloc_id(); + let black = Appearance::basic(Paint::None, Paint::solid(Color::rgb8(0, 0, 0)), 1.0); + doc.insert(Some(layer), 0, Node::path(id, vectorcraft_geom::PathData::from_bezpath(&b), black)).unwrap(); + for version in crate::DxfVersion::ALL.into_iter().filter(|v| v.r2000()) { + let opts = crate::DxfOptions { version, unit: Unit::Points, region: doc.artboards[0].rect, ..crate::DxfOptions::default() }; + let out = crate::export(&doc, &opts).unwrap(); + assert!(std::str::from_utf8(&out.bytes).unwrap().contains("\nLINE\n"), "{version:?}"); + let back = open(&out.bytes, &points()); + let art = leaves(&back.document); + assert_eq!(art.len(), 1, "{version:?}"); + let path = art[0].path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "{version:?}"); + assert!(!path.subpaths[0].closed, "{version:?}"); + let shift = Affine::translate((0.0, 100.0 - height(&back.document))); + let points = path_points(&art[0]); + assert_eq!(points.len(), 17, "{version:?}: one segment"); + let ends = [shift * points[0], shift * points[16]]; + assert!(ends[0].distance(Point::new(20.0, 30.0)) < 1e-6 && ends[1].distance(Point::new(120.0, 70.0)) < 1e-6, "{version:?}: {ends:?}"); + } +} + #[test] fn closed_control_point_splines_stay_closed_through_export_and_import() { // (explicitly closed, ends where it starts): coincident endpoints alone do not close a path. diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 4afe84e332..3fc4bcb3b0 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -233,7 +233,8 @@ impl RasterFormat { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Preserve { /// Type becomes glyph outlines; strokes a plain CAD line can't draw (aligned inside or - /// outside, width profiles, arrowheads, fitted dashes) become their filled outlines; brush + /// outside, width profiles, arrowheads, fitted dashes, dashes offset into their pattern) + /// become their filled outlines; brush /// strokes become their brush art. #[default] Appearance, @@ -277,7 +278,9 @@ pub struct DxfOptions { pub colors: ColorDepth, pub raster: RasterFormat, pub preserve: Preserve, - /// Alter Paths for Appearance: every stroke is written as the filled area it paints. + /// Alter Paths for Appearance: a stroke a CAD line can't draw (one [`Preserve::Appearance`] + /// outlines, one wider than the widest lineweight, or any stroke in R13 and R14, which have + /// no lineweights) is written as the filled area it paints. pub alter_paths: bool, /// Type is written as glyph outlines (always with [`Preserve::Appearance`]). pub outline_text: bool, diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 7ab1d17f83..ea3b8558d7 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -10,7 +10,7 @@ use kurbo::PathEl; use vectorcraft_color::Paint; use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, Node, NodeKind, StrokeLayer, SymbolBoxes, TextKind, TextObject, Unit}; use vectorcraft_effects::stroke; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2}; use crate::aci::nearest_aci; use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed}; @@ -184,6 +184,46 @@ fn circular_subpath(sub: &Sub) -> Option { Some(CircularSub { centre, radius, samples }) } +/// A closed subpath that is the four-cubic circle under an affine map: an ellipse, or a circle +/// scaled out of proportion. `u` and `v` are the conjugate semi-diameters through its first two +/// anchors. +struct EllipticalSub { + centre: Point, + u: Vec2, + v: Vec2, +} + +/// Fit a closed subpath of four cubics to one ellipse. Its anchors give the center and two +/// conjugate semi-diameters; the subpath mapped by their inverse must pass [`circular_subpath`] as +/// the unit circle, so the same tolerance and turn checks apply. +fn elliptical_subpath(sub: &Sub) -> Option { + if !sub.closed || sub.segs.len() != 4 { + return None; + } + let (a0, a1, a2) = (sub.start, sub.segs.first()?.end(), sub.segs.get(1)?.end()); + let centre = a0.midpoint(a2); + let (u, v) = (a0 - centre, a1 - centre); + let det = u.cross(v); + let scale2 = u.hypot2().max(v.hypot2()); + if !det.is_finite() || !scale2.is_finite() || det.abs() <= scale2 * 1e-9 { + return None; + } + let unit = |p: Point| { + let d = p - centre; + Point::new(d.cross(v) / det, u.cross(d) / det) + }; + let mut segs = Vec::with_capacity(4); + for seg in &sub.segs { + let Seg::Cubic(a, b, to) = *seg else { return None }; + segs.push(Seg::Cubic(unit(a), unit(b), unit(to))); + } + let circle = circular_subpath(&Sub { start: unit(sub.start), segs, closed: true })?; + if circle.centre.to_vec2().hypot() > 5e-4 || (circle.radius - 1.0).abs() > 5e-4 { + return None; + } + Some(EllipticalSub { centre, u, v }) +} + fn angle_deg(p: Point, centre: Point) -> f64 { (p.y - centre.y).atan2(p.x - centre.x).to_degrees().rem_euclid(360.0) } @@ -233,6 +273,17 @@ const MAX_ENTITIES: u32 = 10_000_000; const MAX_COORD: f64 = 1e9; const MAX_POINTS: usize = 4_000_000; +/// Do the dashes of `d` start at the start of their pattern, as a linetype's do? A pattern of +/// odd length repeats twice in its linetype. +fn starts_with_pattern(d: &Dash) -> bool { + if !d.is_dashed() || !d.offset.is_finite() { + return true; + } + let period = d.pattern.iter().sum::() * if d.pattern.len() % 2 == 1 { 2.0 } else { 1.0 }; + let phase = d.offset.rem_euclid(period); + phase.min(period - phase) <= period * 1e-9 +} + /// `bp` flattened into polygons (each closing implicitly), consecutive repeats dropped. fn polygons(bp: &BezPath) -> Vec> { // Far outside any drawing, a curve flattens to millions of points at this tolerance. @@ -494,7 +545,7 @@ impl<'a> Scene<'a> { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST { - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); self.nest += 1; self.node(&art, true); @@ -612,8 +663,7 @@ impl<'a> Scene<'a> { /// The DXF lineweight nearest to `width` points (scaled with the drawing when asked). fn lineweight(&mut self, width: f64) -> i32 { - let scale = if self.o.scale_lineweights { self.o.scale } else { 1.0 }; - let hundredths = width * 2540.0 / 72.0 * scale; + let hundredths = self.hundredths(width); let max = LINEWEIGHTS[LINEWEIGHTS.len() - 1]; if hundredths > f64::from(max) + 5.0 { self.warn(WIDE_LINES); @@ -621,6 +671,21 @@ impl<'a> Scene<'a> { LINEWEIGHTS.into_iter().min_by(|a, b| (f64::from(*a) - hundredths).abs().total_cmp(&(f64::from(*b) - hundredths).abs())).unwrap_or(max) } + /// `width` points in hundredths of a millimetre, the unit of DXF lineweights (scaled with + /// the drawing when asked). + fn hundredths(&self, width: f64) -> f64 { + let scale = if self.o.scale_lineweights { self.o.scale } else { 1.0 }; + width * 2540.0 / 72.0 * scale + } + + /// Can a CAD line draw a plain stroke `width` points wide in this version? R12 polylines + /// carry their width, R13 and R14 have no lineweights, and from 2000 a lineweight holds up + /// to 2.11 mm, to the hundredth. + fn line_keeps_width(&self, width: f64) -> bool { + let v = self.o.version; + !v.handles() || (v.r2000() && self.hundredths(width).round() <= f64::from(LINEWEIGHTS[LINEWEIGHTS.len() - 1])) + } + /// A linetype for dash pattern `d` (one per distinct pattern). fn linetype(&mut self, d: &Dash) -> String { let mut lengths: Vec = d.pattern.iter().map(|v| v * self.k).collect(); @@ -673,7 +738,11 @@ impl<'a> Scene<'a> { } let Some(rgb) = self.paint_rgb(&st.paint) else { return }; let plain = stroke::is_plain(st); - if self.o.alter_paths || (appearance && !plain) { + // A linetype has no phase: dashes that start part way into their pattern need outlines. + let lined = plain && st.dash.as_ref().is_none_or(starts_with_pattern); + // Alter Paths for Appearance outlines a stroke only when a line can't draw it. + let altered = self.o.alter_paths && !(lined && self.line_keeps_width(st.width)); + if altered || (appearance && !lined) { let region = stroke::outline_region(&PathData::from_bezpath(bp), rule, st); let style = self.style(rgb, st.opacity, None, None); self.area(®ion.to_bezpath(), FillRule::NonZero, &style, true); @@ -740,9 +809,9 @@ impl<'a> Scene<'a> { self.e.int(98, 0); } - /// Path `bp` as lines: polylines for straight subpaths (and for curves in R12, flattened), - /// cubic splines for curved ones. `width`: the stroke weight, which DXF before 2000 gives - /// polylines as a width. + /// Path `bp` as lines: a line for an open subpath of one straight segment, polylines for + /// other straight subpaths (and for curves in R12, flattened), cubic splines for curved ones. + /// `width`: the stroke weight, which DXF before 2000 gives polylines as a width. fn lines(&mut self, bp: &BezPath, style: &EntityStyle, width: f64) { let v = self.o.version; let width = (!v.r2000() && width > 0.0).then_some(width * self.k); @@ -755,11 +824,17 @@ impl<'a> Scene<'a> { if sub.closed && pts.len() > 2 && pts.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) { pts.pop(); } - self.polyline(&pts, sub.closed, style, width); + // A LINE has no width, so a stroke before 2000 keeps its polyline width. + match (sub.closed, width, pts.as_slice()) { + (false, None, &[a, b]) => self.line(a, b, style), + _ => 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.elliptical(&sub, style) { + // R13 and later write an ellipse as a native ELLIPSE. } else if v.handles() { self.spline(&sub, style); } else { @@ -778,6 +853,16 @@ impl<'a> Scene<'a> { } } + /// A line from `a` to `b` (document space). + fn line(&mut self, a: Point, b: Point, style: &EntityStyle) { + let (a, b) = (self.pt(a), self.pt(b)); + let layer = self.layer.clone(); + let h = self.handle(); + self.e.entity("LINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbLine"); + self.e.xyz(10, a.x, a.y); + self.e.xyz(11, b.x, b.y); + } + /// A polyline through `pts` (document space): lightweight from R14, else a polyline with a /// vertex entity per point. fn polyline(&mut self, pts: &[Point], closed: bool, style: &EntityStyle, width: Option) { @@ -787,7 +872,8 @@ impl<'a> Scene<'a> { let pts: Vec = pts.iter().map(|p| self.pt(*p)).collect(); let layer = self.layer.clone(); let h = self.handle(); - let flags = i64::from(closed); + // Bit 128: a linetype runs on through the vertices instead of restarting at each one. + let flags = i64::from(closed) | if style.linetype.is_some() { 128 } else { 0 }; if self.o.version.lwpolyline() { self.e.entity("LWPOLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbPolyline"); self.e.int(90, pts.len() as i64); @@ -887,6 +973,53 @@ impl<'a> Scene<'a> { true } + /// Write a recognized elliptical subpath as a native DXF ELLIPSE (R13 and later): its center, + /// the end of its major axis relative to the center, and the minor to major ratio. Returns + /// false when the curve is not an ellipse, leaving the caller to write it as a spline. + fn elliptical(&mut self, sub: &Sub, style: &EntityStyle) -> bool { + let Some(last) = sub.segs.last().map(|s| s.end()) else { return false }; + if !sub.closed || last.distance(sub.start) > 1e-9 { + return false; + } + let Some(ellipse) = elliptical_subpath(sub) else { return false }; + let centre = self.to_dxf * ellipse.centre; + let u = self.to_dxf * (ellipse.centre + ellipse.u) - centre; + let v = self.to_dxf * (ellipse.centre + ellipse.v) - centre; + // The semi-axes are the square roots of the eigenvalues of [[a, b], [b, d]] = u u^T + v v^T. + let (a, b, d) = (u.x * u.x + v.x * v.x, u.x * u.y + v.x * v.y, u.y * u.y + v.y * v.y); + let mean = (a + d) / 2.0; + let spread = ((a - d) / 2.0).hypot(b); + let (major, minor) = ((mean + spread).sqrt(), (mean - spread).max(0.0).sqrt()); + let angle = 0.5 * (2.0 * b).atan2(a - d); + let axis = Vec2::new(major * angle.cos(), major * angle.sin()); + let ratio = (minor / major).min(1.0); + // A thinner ellipse stays a spline: DXF readers such as ezdxf need a ratio of 1e-6 or more. + if !centre.x.is_finite() || !centre.y.is_finite() || !axis.x.is_finite() || !axis.y.is_finite() || !ratio.is_finite() || ratio < 1e-6 { + return false; + } + + // The drawing extents take the ellipse's bounding box: half-widths hypot(u.x, v.x) and + // hypot(u.y, v.y) about the center. + let (c, eu, ev) = (ellipse.centre, ellipse.u, ellipse.v); + let (hx, hy) = (eu.x.hypot(ev.x), eu.y.hypot(ev.y)); + for p in [Point::new(c.x - hx, c.y), Point::new(c.x + hx, c.y), Point::new(c.x, c.y - hy), Point::new(c.x, c.y + hy)] { + self.pt(p); + } + + let layer = self.layer.clone(); + let h = self.handle(); + self.e.entity("ELLIPSE", h, fixed::MODEL_RECORD, &layer, style, "AcDbEllipse"); + self.e.xyz(10, centre.x, centre.y); + self.e.xyz(11, axis.x, axis.y); + self.e.normal(); + // The ratio and the end parameter are written in full: rounded to six decimals, a thin + // ellipse's minor axis would change size, and a whole turn would read back as an open curve. + self.e.raw(40, &ratio.to_string()); + self.e.num(41, 0.0); + self.e.raw(42, &std::f64::consts::TAU.to_string()); + 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) { @@ -929,7 +1062,8 @@ impl<'a> Scene<'a> { } /// Type: glyph outlines (Preserve Appearance, Outline Text, type on a path), else one text - /// entity per run of each line. + /// entity per run of each line, whose height (group 40) is [`CAP_HEIGHT`] times the em size its + /// run is drawn at ([`vectorcraft_text::FontDb::font_heights_resolved`]). fn text(&mut self, n: &Node, t: &TextObject) { let outline = self.o.preserve == Preserve::Appearance || self.o.outline_text || matches!(t.kind, TextKind::OnPath { .. }); if outline { @@ -941,6 +1075,8 @@ impl<'a> Scene<'a> { if !n.appearance.items.is_empty() { self.warn(TYPE_ITEMS); } + let resolved = vectorcraft_text::FontDb::global().font_heights_resolved(t); + let t = &*resolved; let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); let plain = t.plain_text(); let xf = self.to_dxf * t.xf; diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 30a8d1a819..f1b537b70b 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, CharStyle, Dash, Document, ImageBlob, ImageObject, Node, NodeKind, TextObject, Unit}; -use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, Shape, shapes}; use crate::*; @@ -125,6 +125,71 @@ fn every_version_declares_its_acadver_and_is_well_formed() { assert_eq!(DxfVersion::from_id("2019"), None); } +/// The structure strict readers (Autodesk Fusion, #3085) need: the required sections and table +/// entries, handles that every reference resolves to, and LAYOUT objects with only the group codes +/// the DXF Reference defines for PLOTSETTINGS and LAYOUT (AutoCAD DXF Reference, OBJECTS section: +/// https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-1113675E-AB07-4567-BD47-B7FBE7290D1C). +#[test] +fn r2000_and_later_files_have_the_structure_cad_apps_require() { + use std::collections::HashSet; + // Common object codes, then AcDbPlotSettings, then AcDbLayout (76 is the shade plot mode in + // the first and the UCS type in the second). + let layout_codes: HashSet = [0, 5, 102, 330, 360, 100] + .into_iter() + .chain([1, 2, 4, 6, 7, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 140, 141, 142, 143, 70, 72, 73, 74, 75, 76, 77, 78, 147, 148, 149, 333]) + .chain([71, 10, 20, 11, 21, 12, 22, 32, 14, 24, 34, 15, 25, 35, 146, 13, 23, 33, 16, 26, 36, 17, 27, 37, 331, 345, 346]) + .collect(); + let d = shapes_doc(); + for v in DxfVersion::ALL.into_iter().filter(|v| *v >= DxfVersion::R2000) { + let out = export(&d, &DxfOptions { version: v, ..opts(&d) }).unwrap(); + let p = pairs(&out.bytes); + for name in ["HEADER", "CLASSES", "TABLES", "BLOCKS", "ENTITIES", "OBJECTS"] { + assert!(p.windows(2).any(|w| w[0] == (0, "SECTION".into()) && w[1] == (2, name.into())), "{v:?}: {name} section"); + } + let tables = section(&p, "TABLES"); + let names = |k: &str| -> Vec { tables.iter().filter(|o| kind(o) == k).filter_map(|o| get(o, 2).map(str::to_string)).collect() }; + for (k, want) in [ + ("LTYPE", "ByBlock"), + ("LTYPE", "ByLayer"), + ("LTYPE", "Continuous"), + ("LAYER", "0"), + ("STYLE", "Standard"), + ("APPID", "ACAD"), + ("DIMSTYLE", "Standard"), + ("BLOCK_RECORD", "*Model_Space"), + ("BLOCK_RECORD", "*Paper_Space"), + ] { + assert!(names(k).iter().any(|n| n == want), "{v:?}: {k} {want}"); + } + // Every object after the header has a handle below $HANDSEED, and every reference to + // another object (owner 330, soft/hard pointers 340/350/390) names one of them. + let body = &p[p.iter().position(|x| *x == (0, "ENDSEC".into())).unwrap()..]; + let handles: HashSet = body.iter().filter(|x| x.0 == 5 || x.0 == 105).map(|x| u32::from_str_radix(&x.1, 16).unwrap()).collect(); + let seed = u32::from_str_radix(&header(&p, "$HANDSEED").unwrap(), 16).unwrap(); + assert!(handles.iter().all(|h| *h < seed), "{v:?}: handles below the seed"); + for (code, value) in body.iter().filter(|x| matches!(x.0, 330 | 340 | 350 | 390)) { + let h = u32::from_str_radix(value, 16).unwrap(); + assert!(h == 0 || handles.contains(&h), "{v:?}: group {code} points at missing handle {value}"); + } + let objects = section(&p, "OBJECTS"); + let layouts: Vec<&Pairs> = objects.iter().filter(|o| kind(o) == "LAYOUT").collect(); + assert_eq!(layouts.len(), 2, "{v:?}: Model and Layout1"); + for l in &layouts { + let bad: Vec = l.iter().map(|x| x.0).filter(|c| !layout_codes.contains(c)).collect(); + assert!(bad.is_empty(), "{v:?}: LAYOUT has group codes the DXF Reference doesn't define: {bad:?}"); + // The paper image origin is 148 (x) and 149 (y). + assert!(get(l, 148).is_some() && get(l, 149).is_some(), "{v:?}: paper image origin"); + // Flag 1024 marks the model space layout, and only it. + let name = l.iter().skip_while(|x| x.1 != "AcDbLayout").find(|x| x.0 == 1).map(|x| x.1.as_str()); + let flags: i64 = get(l, 70).unwrap().parse().unwrap(); + assert_eq!(flags & 1024 != 0, name == Some("Model"), "{v:?}: model type flag of {name:?}"); + } + // The plot style placeholder carries only the common object codes. + let holder = objects.iter().find(|o| kind(o) == "ACDBPLACEHOLDER").expect("placeholder"); + assert!(holder.iter().all(|x| matches!(x.0, 0 | 5 | 102 | 330)), "{v:?}: placeholder {holder:?}"); + } +} + #[test] fn r12_viewport_has_no_duplicate_group_codes() { let d = shapes_doc(); @@ -208,10 +273,168 @@ fn circles_and_circular_arcs_are_native_dxf_entities() { 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"]); +/// The path `p` with `xf` applied. +fn transformed(p: &PathData, xf: Affine) -> PathData { + PathData::from_bezpath(&(xf * p.to_bezpath())) +} + +fn close_to(a: &[f64], b: &[f64], tol: f64) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol) +} + +#[test] +fn ellipses_and_unevenly_scaled_circles_are_native_ellipses() { + let circle = shapes::ellipse(Rect::new(20.0, 20.0, 80.0, 80.0)); + let d = doc_with(|d| { + let stroke = || Paint::solid(Color::BLACK); + vec![ + // 80 × 40 pt about (60, 40): DXF center (60, 60), major axis (40, 0), ratio 0.5. + path(d, shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), Paint::None, stroke(), 1.0), + // A 60 pt circle scaled 150% across about (50, 50): 90 × 60 pt, ratio 2/3. + path( + d, + transformed(&circle, Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(1.5, 1.0) * Affine::translate((-50.0, -50.0))), + Paint::None, + stroke(), + 1.0, + ), + // The first ellipse turned 30° about its center, filled: the outline is the ellipse too. + path( + d, + transformed(&shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), Affine::rotate_about(30f64.to_radians(), Point::new(60.0, 40.0))), + Paint::solid(Color::BLACK), + Paint::None, + 0.0, + ), + ] + }); + for version in DxfVersion::ALL.into_iter().filter(|version| *version >= DxfVersion::R13) { + let out = export(&d, &DxfOptions { version, ..opts(&d) }).unwrap(); + let e = entities(&out); + assert_eq!(e.iter().map(|x| kind(x)).collect::>(), ["ELLIPSE", "ELLIPSE", "ELLIPSE", "HATCH"], "{version:?}"); + let ellipse = |x: &Pairs| (all(x, 10), all(x, 20), all(x, 11), all(x, 21), all(x, 40), all(x, 41), all(x, 42)); + let (cx, cy, mx, my, ratio, start, end) = ellipse(&e[0]); + assert_eq!((cx, cy, mx, my, ratio), (vec![60.0], vec![60.0], vec![40.0], vec![0.0], vec![0.5]), "{version:?}"); + assert!(close_to(&start, &[0.0], 1e-9) && close_to(&end, &[std::f64::consts::TAU], 1e-12), "{version:?}: a whole turn"); + let (cx, cy, mx, my, ratio, ..) = ellipse(&e[1]); + assert!(close_to(&[cx, cy, mx, my, ratio].concat(), &[50.0, 50.0, 45.0, 0.0, 2.0 / 3.0], 1e-6), "{version:?}: {:?}", e[1]); + // Turned 30° counterclockwise on screen, so clockwise with DXF's y up. + let (cx, cy, mx, my, ratio, ..) = ellipse(&e[2]); + let (cos, sin) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + assert!(close_to(&[cx, cy, mx, my, ratio].concat(), &[60.0, 60.0, 40.0 * cos, -40.0 * sin, 0.5], 1e-6), "{version:?}: {:?}", e[2]); + assert!(e[0].contains(&(100, "AcDbEllipse".into())), "{version:?}"); + } + // R12 has no ELLIPSE: the curves are flattened polylines. + let r12 = kinds(&export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap()); + assert!(!r12.iter().any(|k| k == "ELLIPSE") && r12.iter().any(|k| k == "POLYLINE"), "{r12:?}"); + // A thin ellipse keeps its ratio in full (six decimals would write 0.000002). + let thin = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(0.0, 50.0, 200.0, 50.0003)), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + let e = entities(&export(&thin, &opts(&thin)).unwrap()); + assert_eq!(kind(&e[0]), "ELLIPSE"); + assert!(close_to(&all(&e[0], 40), &[1.5e-6], 1e-10), "{:?}", e[0]); +} + +#[test] +fn exported_ellipses_read_back_as_the_same_ellipse() { + let xf = Affine::rotate_about(30f64.to_radians(), Point::new(60.0, 40.0)); + let d = doc_with(|d| { + vec![path(d, transformed(&shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), xf), Paint::None, Paint::solid(Color::BLACK), 1.0)] + }); + let out = export(&d, &opts(&d)).unwrap(); + assert_eq!(kinds(&out), ["ELLIPSE"]); + let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }; + let back = import(&out.bytes, &o).unwrap().document; + let mut paths = vec![]; + back.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + paths.push(path.to_bezpath()); + } + }); + assert_eq!(paths.len(), 1); + assert!(paths[0].elements().last().is_some_and(|el| matches!(el, kurbo::PathEl::ClosePath)), "the ellipse reads back closed"); + // Every point of the curve read back lies on the 80 × 40 pt ellipse turned 30°, once both are centered. + let bp = &paths[0]; + let found = bp.bounding_box().center(); + let inverse = xf.inverse(); + let original = Point::new(60.0, 40.0); + for seg in bp.segments() { + for i in 0..=16 { + let p = seg.eval(f64::from(i) / 16.0) - found.to_vec2() + original.to_vec2(); + let q = inverse * p; + let r = ((q.x - 60.0) / 40.0).hypot((q.y - 40.0) / 20.0); + assert!((r - 1.0).abs() < 1e-3, "{p:?} is off the ellipse ({r})"); + } + } +} + +#[test] +fn closed_four_cubic_shapes_that_are_not_writable_ellipses_stay_splines() { + // A rounded square: four cubics through the ellipse's anchors with longer handles. + let (c, r, k) = (Point::new(50.0, 50.0), 30.0, 30.0 * 0.8); + let mut squircle = vectorcraft_geom::BezPath::new(); + squircle.move_to(Point::new(c.x + r, c.y)); + squircle.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)); + squircle.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)); + squircle.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)); + squircle.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)); + squircle.close_path(); + // An egg: one half wider than the other. + let egg = shapes::ellipse(Rect::new(110.0, 20.0, 190.0, 60.0)).to_bezpath(); + let mut els: Vec = egg.elements().to_vec(); + if let Some(kurbo::PathEl::CurveTo(a, b, _)) = els.get_mut(1) { + a.x -= 10.0; + b.x -= 10.0; + } + let d = doc_with(|d| { + vec![ + path(d, PathData::from_bezpath(&squircle), Paint::None, Paint::solid(Color::BLACK), 1.0), + path(d, PathData::from_bezpath(&kurbo::BezPath::from_vec(els)), Paint::None, Paint::solid(Color::BLACK), 1.0), + // An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6). + path(d, shapes::ellipse(Rect::new(0.0, 90.0, 200.0, 90.0001)), Paint::None, Paint::solid(Color::BLACK), 1.0), + ] + }); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "SPLINE"]); +} + +#[test] +fn a_lone_straight_segment_is_a_line() { + let segment = |closed: bool, extra: Option| { + let mut b = vectorcraft_geom::BezPath::new(); + b.move_to(Point::new(20.0, 30.0)); + b.line_to(Point::new(120.0, 70.0)); + if let Some(p) = extra { + b.line_to(p); + } + if closed { + b.close_path(); + } + PathData::from_bezpath(&b) + }; + let d = doc_with(|d| vec![path(d, segment(false, None), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + for version in DxfVersion::ALL.into_iter().filter(|v| v.r2000()) { + let e = entities(&export(&d, &DxfOptions { version, ..opts(&d) }).unwrap()); + assert_eq!(e.iter().map(|x| kind(x)).collect::>(), ["LINE"], "{version:?}"); + assert_eq!(e[0].iter().rfind(|p| p.0 == 100).map(|p| p.1.as_str()), Some("AcDbLine"), "{version:?}"); + assert_eq!((all(&e[0], 10), all(&e[0], 20)), (vec![20.0], vec![70.0]), "{version:?}: y up from the artboard's bottom"); + assert_eq!((all(&e[0], 11), all(&e[0], 21)), (vec![120.0], vec![30.0]), "{version:?}"); + } + + // Without a width (R12 writes a fill as its outline), R12 writes a LINE too; a stroke weight + // before 2000 keeps its polyline width. + let filled = doc_with(|d| vec![path(d, segment(false, None), Paint::solid(Color::BLACK), Paint::None, 0.0)]); + let r12 = |d: &Document| kinds(&export(d, &DxfOptions { version: DxfVersion::R12, ..opts(d) }).unwrap()); + assert_eq!(r12(&filled), ["LINE"]); + assert_eq!(r12(&d), ["POLYLINE", "VERTEX", "VERTEX", "SEQEND"]); + let r14 = entities(&export(&d, &DxfOptions { version: DxfVersion::R14, ..opts(&d) }).unwrap()); + assert_eq!((kind(&r14[0]), get(&r14[0], 43)), ("LWPOLYLINE", Some("1"))); + + // A closed segment and two segments stay polylines. + for p in [segment(true, None), segment(false, Some(Point::new(150.0, 20.0)))] { + let d = doc_with(|d| vec![path(d, p, Paint::None, Paint::solid(Color::BLACK), 1.0)]); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["LWPOLYLINE"]); + } } #[test] @@ -453,14 +676,44 @@ fn dashes_become_linetypes_and_opacity_transparency() { #[test] fn alter_paths_writes_strokes_as_filled_outlines() { - let d = shapes_doc(); - let out = export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap(); - // Each fill and stroke: its outlines, then its hatch. let fill = ["LWPOLYLINE", "HATCH"]; let rect_stroke = ["LWPOLYLINE", "LWPOLYLINE", "HATCH"]; + // Strokes a lineweight draws stay lines: the rectangle, the circle and an open arc. + let mut d = shapes_doc(); + let c = Point::new(150.0, 95.0); + let k = 20.0 * shapes::KAPPA; + let mut arc = vectorcraft_geom::BezPath::new(); + arc.move_to(Point::new(c.x + 20.0, c.y)); + arc.curve_to(Point::new(c.x + 20.0, c.y - k), Point::new(c.x + k, c.y - 20.0), Point::new(c.x, c.y - 20.0)); + let arc = path(&mut d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, arc).unwrap(); + let out = export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&out), [&fill[..], &["LWPOLYLINE", "CIRCLE", "ARC"]].concat()); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + // R12 polylines carry any width, so its strokes stay lines too. + let r12 = export(&d, &DxfOptions { alter_paths: true, version: DxfVersion::R12, ..opts(&d) }).unwrap(); + assert!(!kinds(&r12).iter().any(|k| k == "HATCH")); + assert!(entities(&r12).iter().any(|e| kind(e) == "POLYLINE" && get(e, 40) == Some("2"))); + // R13 and R14 have no lineweights: every stroke becomes its outline, then its hatch. + let d = shapes_doc(); + let out = export(&d, &DxfOptions { alter_paths: true, version: DxfVersion::R14, ..opts(&d) }).unwrap(); 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")); + // A stroke wider than the widest lineweight (2.11 mm) is outlined at its true width. + let wide = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 8.0)]); + let out = export(&wide, &DxfOptions { alter_paths: true, ..opts(&wide) }).unwrap(); + assert_eq!(kinds(&out), rect_stroke); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let lines = export(&wide, &opts(&wide)).unwrap(); + assert_eq!(kinds(&lines), ["LWPOLYLINE"]); + assert!(lines.warnings.iter().any(|w| w.contains("2.11 mm"))); + // To the hundredth of a millimetre: 6 pt (2.117 mm) is outlined, 5.98 pt (2.110 mm) is a line. + for (width, expected) in [(6.0, &rect_stroke[..]), (5.98, &["LWPOLYLINE"][..])] { + let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), width)]); + assert_eq!(kinds(&export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap()), expected, "{width} pt"); + } // Preserve Appearance outlines only the strokes a line can't draw. let mut d = shapes_doc(); let rect = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap(); @@ -471,6 +724,65 @@ fn alter_paths_writes_strokes_as_filled_outlines() { let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); assert_eq!(kinds(&editable), ["LWPOLYLINE", "HATCH", "LWPOLYLINE", "CIRCLE"]); assert!(editable.warnings.iter().any(|w| w.contains("stroke alignment"))); + // With Maximize Editability, Alter Paths outlines that stroke and keeps the circle a line. + let altered = export(&d, &DxfOptions { preserve: Preserve::Editability, alter_paths: true, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&altered), [&fill[..], &rect_stroke, &["CIRCLE"]].concat()); + assert!(altered.warnings.is_empty(), "{:?}", altered.warnings); +} + +#[test] +fn dashes_that_start_part_way_into_their_pattern_are_outlined() { + let dashed = |offset: f64| { + doc_with(|d| { + let mut n = path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0); + if let Some(st) = n.appearance.stroke_mut() { + st.dash = Some(Dash { pattern: vec![6.0, 3.0, 2.0], offset, align_corners: false }); + } + vec![n] + }) + }; + // A linetype starts at the start of its pattern: an offset of a whole period (the odd + // pattern twice) keeps the line, any other offset needs the dashes' outlines and a hatch. + for (offset, outlined) in [(0.0, false), (22.0, false), (4.0, true), (11.0, true)] { + let d = dashed(offset); + let k = kinds(&export(&d, &opts(&d)).unwrap()); + if outlined { + assert!(k.len() > 2 && k.last().is_some_and(|k| k == "HATCH"), "offset {offset}: {k:?}"); + } else { + assert_eq!(k, ["LWPOLYLINE"], "offset {offset}"); + } + let altered = kinds(&export(&d, &DxfOptions { alter_paths: true, ..opts(&d) }).unwrap()); + assert_eq!(altered, k, "offset {offset}, Alter Paths"); + } + // Maximize Editability keeps the line and its linetype. + let d = dashed(4.0); + let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + assert_eq!(kinds(&editable), ["LWPOLYLINE"]); + assert_eq!(get(&entities(&editable)[0], 6), Some("DASHED1")); +} + +#[test] +fn dashed_polylines_continue_their_pattern_around_corners() { + let rect = |dash: Option| { + doc_with(|d| { + let mut n = path(d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0); + if let Some(st) = n.appearance.stroke_mut() { + st.dash = dash.clone(); + } + vec![n] + }) + }; + let flags = |out: &DxfOutput| entities(out).first().and_then(|e| get(e, 70).map(str::to_string)); + // Group 70 bit 128 makes the linetype run on through the vertices instead of restarting + // at each one; a solid polyline keeps only its closed bit. + let dashed = rect(Some(Dash { pattern: vec![6.0, 3.0], offset: 0.0, align_corners: false })); + for o in [opts(&dashed), DxfOptions { alter_paths: true, ..opts(&dashed) }, DxfOptions { preserve: Preserve::Editability, ..opts(&dashed) }] { + assert_eq!(flags(&export(&dashed, &o).unwrap()).as_deref(), Some("129")); + } + let r12 = export(&dashed, &DxfOptions { version: DxfVersion::R12, ..opts(&dashed) }).unwrap(); + assert_eq!((kinds(&r12).first().map(String::as_str), flags(&r12).as_deref()), (Some("POLYLINE"), Some("129"))); + let solid = rect(None); + assert_eq!(flags(&export(&solid, &opts(&solid)).unwrap()).as_deref(), Some("1")); } fn text_doc(text: &str, size: f64) -> Document { @@ -594,6 +906,23 @@ fn text_outside_ascii_is_escaped_before_2007() { assert_eq!(text(DxfVersion::R2018), "Größe"); } +/// Type whose font size measures the cap height is written at the em size it is drawn at: 14 pt +/// measuring a 0.7 em cap height is 20 pt type, whose TEXT height is 14. +#[test] +fn a_font_height_reference_is_written_as_the_size_drawn() { + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + let mut d = text_doc("Plan A", 14.0); + let id = d.layers[0].children().and_then(|c| c.first()).map(|n| n.id).unwrap(); + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.runs[0].style.font_family = HEIGHT_FAMILY.into(); + t.runs[0].style.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight; + } + let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + let e = entities(&editable); + assert!((all(&e[0], 40)[0] - 14.0).abs() < 1e-6, "{:?}", all(&e[0], 40)); +} + #[test] fn images_link_png_or_jpeg_files() { let mut png = vec![]; @@ -674,7 +1003,7 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { // while the 20 × 20 square around the origin, moved to (-60, -60) to (-40, -40), is off it. let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Far".into(), xf: Affine::translate((-50.0, -50.0)) })]); let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); - d.symbols.push(vectorcraft_doc::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let o = DxfOptions { crop: true, ..opts(&d) }; assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); } diff --git a/crates/cad/src/writer.rs b/crates/cad/src/writer.rs index 665f8576f1..6ba7e5a35d 100644 --- a/crates/cad/src/writer.rs +++ b/crates/cad/src/writer.rs @@ -564,7 +564,10 @@ impl Drawing { c.handle(350, fixed::PLOT_NORMAL); c.raw(100, "AcDbDictionaryWithDefault"); c.handle(340, fixed::PLOT_NORMAL); - c.object("ACDBPLACEHOLDER", fixed::PLOT_NORMAL, fixed::PLOT_STYLES, "AcDbPlaceHolder"); + // A placeholder has no data and no subclass marker of its own. + c.raw(0, "ACDBPLACEHOLDER"); + c.handle(5, fixed::PLOT_NORMAL); + c.handle(330, fixed::PLOT_STYLES); self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD); self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD); } @@ -618,14 +621,23 @@ impl Drawing { c.num(141, 0.0); c.num(142, 1.0); c.num(143, 1.0); - c.int(70, 688); + // Plot flags; 1024 marks the model space layout. + c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 }); c.int(72, 1); c.int(73, 0); c.int(74, 5); c.raw(7, ""); c.int(75, 16); + if self.version.true_color() { + // Shade plot mode (as displayed), resolution level (normal) and custom DPI. + c.int(76, 0); + c.int(77, 2); + c.int(78, 300); + } c.num(147, 1.0); - c.xy(148, 0.0, 0.0); + // The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158. + c.num(148, 0.0); + c.num(149, 0.0); c.raw(100, "AcDbLayout"); c.raw(1, name); c.int(70, 1); diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8201b8b97f..64f42f25b9 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -149,11 +149,20 @@ impl IccProfile { /// Device values (RGB / CMYK / Gray, 0..1) → sRGB. pub fn to_srgb(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + let mut src = [0.0f32; 4]; + let channels = self.channels(); + src.get_mut(..channels)?.iter_mut().zip(v.iter()).for_each(|(dst, value)| *dst = *value); + self.to_srgb_into(src.get(..channels)?, intent) + } + + /// Convert an exact-width device pixel using the cached transform and stack storage. + pub fn to_srgb_into(&self, v: &[f32], intent: Intent) -> Option<[f32; 3]> { + if v.len() != self.channels() { + return None; + } let xf = self.to_xf(intent)?; - let mut src = v.to_vec(); - src.resize(self.channels(), 0.0); let mut dst = [0.0f32; 3]; - xf.transform(&src, &mut dst).ok()?; + xf.transform(v, &mut dst).ok()?; Some(dst.map(|x| x.clamp(0.0, 1.0))) } diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 528d560336..e44b0be9ea 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -78,6 +78,14 @@ const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0; /// Most times each half of a Perceptual gradient's segment (either side of its midpoint) is /// halved to keep within [`PERCEPTUAL_TOLERANCE`]. const PERCEPTUAL_DEPTH: u32 = 10; +/// How many times [`Gradient::ink_tints`] halves the range of tints it searches: to within +/// 1/65536 of a tint, finer than the 1/255 steps PDF writes. +const TINT_STEPS: u32 = 16; +/// The least OKLab lightness by which an ink at 100% must differ from paper white for +/// [`Gradient::ink_tints`] to tell its tints apart by lightness. +const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0; +/// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for. +const MAX_INK_TINTS: usize = 4096; /// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly /// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved @@ -100,6 +108,30 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: } } +/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a` +/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½). +fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec { + let mut vs = Vec::new(); + perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs); + vs.push(0.5); + perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs); + vs +} + +/// The offset of mix position `v` between stops `a` and `b`, placed through `a`'s midpoint +/// (`v` = ½ at the midpoint) as [`Gradient::sample`] maps it. +fn curve_offset(a: &GradientStop, b: &GradientStop, v: f32) -> f32 { + let m = a.midpoint.clamp(0.01, 0.99); + let u = if v == 0.5 { + a.midpoint + } else if v < 0.5 { + 2.0 * v * m + } else { + m + (v - 0.5) * 2.0 * (1.0 - m) + }; + a.offset + (b.offset - a.offset) * u +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GradientStop { /// 0..=1 along the gradient. @@ -262,21 +294,9 @@ impl Gradient { // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the // midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them. let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| { - let mut vs = Vec::new(); - perceptual_steps(&s.color, &n.color, (0.0, 0.5), 1, &mut vs); - vs.push(0.5); - perceptual_steps(&s.color, &n.color, (0.5, 1.0), 1, &mut vs); - let m = s.midpoint.clamp(0.01, 0.99); - vs.into_iter().map(move |v| { + perceptual_mixes(s, n).into_iter().map(move |v| { let mid = v == 0.5; - let u = if mid { - s.midpoint - } else if v < 0.5 { - 2.0 * v * m - } else { - m + (v - 0.5) * 2.0 * (1.0 - m) - }; - let t = s.offset + (n.offset - s.offset) * u; + let t = curve_offset(s, n, v); let o = s.opacity + (n.opacity - s.opacity) * v; (t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint)) }) @@ -284,6 +304,84 @@ impl Gradient { std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten()) }) } + /// A gradient of tints of one ink `ink` (its color at 100%; paper white is 0% of it) as + /// (offset, tint, opacity) at each of [`Self::expanded_stops`]: the tint (0..1) whose OKLab + /// lightness is the lightness of the color there, found to [`TINT_STEPS`] halvings. Mixed + /// linearly between them, the tints follow a Perceptual gradient's curve. `None` when the + /// ink's lightness is within [`MIN_INK_LIGHTNESS_SPAN`] of paper white's (a white or nearly + /// white ink), so lightness does not tell its tints apart, and when the curve has more than + /// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + pub fn ink_tints(&self, ink: &Color) -> Option> { + use crate::libraries::srgb_to_oklab; + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + if lightness(&ink.tinted(0.0)) - lightness(ink) < MIN_INK_LIGHTNESS_SPAN { + return None; + } + let curve: Vec<_> = self.expanded().take(MAX_INK_TINTS + 1).collect(); + if curve.len() > MAX_INK_TINTS { + return None; + } + let tint = |c: &Color| { + let want = lightness(c); + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..TINT_STEPS { + let mid = (lo + hi) / 2.0; + if lightness(&ink.tinted(mid)) > want { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 + }; + Some(curve.into_iter().map(|(t, c, o, _)| (t, tint(&c), o)).collect()) + } + /// Does the gradient's curve ([`Self::expanded`]) have at most [`MAX_INK_TINTS`] stops, so + /// [`Self::ink_tints`] finds tints for it? + pub fn fits_ink_tints(&self) -> bool { + self.expanded().nth(MAX_INK_TINTS).is_none() + } + /// A Perceptual gradient's curve ([`Self::expanded_stops`]) as mixes of its stops' inks: + /// (offset, `i`, weight, opacity) at each stop on it, where the inks there are those of stop + /// `i` and stop `i + 1` mixed linearly at the weight (0..1; 0 on the gradient's own stops). + /// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab + /// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix + /// position itself when the two colors' lightness differs by less than + /// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than + /// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + pub fn ink_mixes(&self) -> Option> { + use crate::libraries::srgb_to_oklab; + if self.method.is_classic() || !self.fits_ink_tints() { + return None; + } + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + let mut out = Vec::new(); + for (i, s) in self.stops.iter().enumerate() { + out.push((s.offset, i, 0.0, s.opacity)); + let Some(n) = self.stops.get(i + 1) else { continue }; + let (l0, l1) = (lightness(&s.color), lightness(&n.color)); + for v in perceptual_mixes(s, n) { + let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN { + v + } else { + let want = lightness(&self.method.mix(&s.color, &n.color, v)); + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..TINT_STEPS { + let mid = (lo + hi) / 2.0; + // The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one. + if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 + }; + out.push((curve_offset(s, n, v), i, weight, s.opacity + (n.opacity - s.opacity) * v)); + } + } + Some(out) + } /// The same ramp the other way round: the stops in reverse order at mirrored offsets, each /// segment's midpoint mirrored with it. pub fn reverse(&mut self) { diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 19e9f44fc7..ab195b347c 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -455,3 +455,71 @@ fn perceptual_gradients_draw_as_pixels() { assert!(GradientPaint::new(radial).draws_as_pixels(fill)); } } + +/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on +/// the curve has the lightness of the color mixed there, so the tints between the stops are not +/// a straight line. +#[test] +fn ink_tints_follow_the_perceptual_curve() { + use crate::libraries::srgb_to_oklab; + let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0); + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, ink.tinted(0.8)), GradientStop::new(1.0, Color::WHITE)]); + g.method = GradientMethod::Perceptual; + assert!(g.fits_ink_tints()); + let tints = g.ink_tints(&ink).expect("a magenta ink's tints differ in lightness"); + assert!(tints.len() > 2, "the curve's stops: {tints:?}"); + let (first, last) = (tints[0], tints[tints.len() - 1]); + assert!((first.0, last.0) == (0.0, 1.0) && (first.1 - 0.8).abs() < 1e-4 && last.1 < 1e-4, "{tints:?}"); + assert!(tints.windows(2).all(|w| w[0].0 <= w[1].0 && w[0].1 >= w[1].1), "in order, lighter along the way: {tints:?}"); + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + for (t, tint, _) in &tints { + let want = lightness(&g.sample(*t).0); + assert!((lightness(&ink.tinted(*tint)) - want).abs() < 1e-3, "at {t}: tint {tint}"); + } + let mid = tints.iter().find(|s| (s.0 - 0.5).abs() < 1e-6).expect("the midpoint"); + assert!((mid.1 - 0.4).abs() > 0.01, "not halfway in tint: {mid:?}"); + // A white ink's tints all have paper white's lightness: no tints by lightness. + assert_eq!(g.ink_tints(&Color::WHITE), None); + // More stops on the curve than MAX_INK_TINTS: no tints. + let n = MAX_INK_TINTS + 1; + g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { ink } else { Color::WHITE })).collect(); + assert_eq!(g.ink_tints(&ink), None); + assert!(!g.fits_ink_tints()); +} + +/// A Perceptual gradient's curve as mixes of its stops' inks: the stops on the curve at their +/// offsets, each weighted so the two stops' colors mixed in display RGB have the lightness of +/// the color on the curve there. +#[test] +fn ink_mixes_follow_the_perceptual_curve() { + use crate::libraries::srgb_to_oklab; + let (magenta, yellow) = (Color::cmyk(0.0, 1.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.6, 0.0)); + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, magenta), GradientStop::new(1.0, yellow)]); + g.stops[0].midpoint = 0.3; + assert_eq!(g.ink_mixes(), None, "a Classic gradient"); + g.method = GradientMethod::Perceptual; + let mixes = g.ink_mixes().expect("a Perceptual gradient's curve"); + let curve = g.expanded_stops(); + assert_eq!(mixes.len(), curve.len(), "a mix for each stop on the curve"); + assert_eq!((mixes[0], mixes[mixes.len() - 1]), ((0.0, 0, 0.0, 1.0), (1.0, 1, 0.0, 1.0)), "the gradient's own stops"); + let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0]; + for ((t, i, w, _), (ct, c, _)) in mixes.iter().zip(&curve) { + assert!((t - ct).abs() < 1e-6, "{t} on the curve at {ct}"); + if *i == 0 && *t > 0.0 { + let mixed = GradientMethod::Classic.mix(&magenta, &yellow, *w); + assert!((lightness(&mixed) - lightness(c)).abs() < 1e-3, "at {t}: weight {w}"); + } + } + let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint"); + assert!((mid.2 - 0.5).abs() > 0.01, "not halfway at the midpoint: {mid:?}"); + assert!(mixes.windows(2).all(|w| w[0].0 <= w[1].0), "in order: {mixes:?}"); + // Two colors of one lightness: the weights are the mix positions. + g.stops[1].color = magenta; + let mixes = g.ink_mixes().expect("the curve"); + let mid = mixes.iter().find(|m| (m.0 - 0.3).abs() < 1e-6).expect("the midpoint"); + assert!((mid.2 - 0.5).abs() < 1e-6, "{mid:?}"); + // More stops on the curve than MAX_INK_TINTS: no mixes. + let n = MAX_INK_TINTS + 1; + g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect(); + assert_eq!(g.ink_mixes(), None); +} diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index ccae9666bd..09142df0c0 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -53,6 +53,15 @@ impl WidthProfile { // Two swells between narrow necks. ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] }, ]; + /// The widest the stroke gets, as a multiple of its weight: the largest total of the left and + /// right factors at any of the points (between them the profile is straight), 1 for a profile + /// without points. + pub fn widest(&self) -> f64 { + if self.points.is_empty() { + return 1.0; + } + self.points.iter().map(|&(_, l, r)| (l.max(0.0) + r.max(0.0)) / 2.0).fold(0.0, f64::max) + } /// The built-in profile with this id. pub fn preset(id: &str) -> Option { Self::PRESETS.iter().find(|p| p.id == id).map(|p| Self { points: p.points.to_vec() }) diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs index b78b8eb014..6d5d50d4d4 100644 --- a/crates/doc/src/artboard.rs +++ b/crates/doc/src/artboard.rs @@ -35,8 +35,8 @@ pub struct Artboard { pub video_ruler_pixel_aspect_ratio: f64, /// Background color (Properties › Artboards › Fill, Artboard Options). The canvas draws the /// artboard's paper in it, multiplied with the Simulate Colored Paper color while that is on; - /// without one the paper is white, or the Simulate Colored Paper color. Exports and print leave - /// it out. + /// without one the paper is white, or the Simulate Colored Paper color. Exports and print draw + /// it behind the art ([`super::Document::with_artboard_fills`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub color: Option, } @@ -77,6 +77,37 @@ impl Artboard { } } +impl super::Document { + /// A copy for output with the background colors ([`Artboard::color`]) of the artboards at + /// `indices` drawn behind all the art: each a rectangle of its artboard filled with its color + /// (in the color's own model), on a layer of their own (Artboard Fill) below the + /// others. `None` when none of them has a color. + pub fn with_artboard_fills(&self, indices: impl IntoIterator) -> Option { + let fills: Vec<(Rect, vectorcraft_color::Color)> = indices + .into_iter() + .filter_map(|i| { + let a = self.artboards.get(i)?; + Some((a.rect, a.color?)) + }) + .collect(); + if fills.is_empty() { + return None; + } + let mut d = self.clone(); + let mut layer = Node::layer(d.alloc_id(), "Artboard Fill", super::LayerColor::Preset(0)); + let paths: Vec> = fills + .into_iter() + .map(|(r, c)| { + let look = super::Appearance::basic(vectorcraft_color::Paint::solid(c), vectorcraft_color::Paint::None, 0.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look)) + }) + .collect(); + *layer.children_mut()? = paths; + d.layers.insert(0, Arc::new(layer)); + Some(d) + } +} + /// A document's locked artboards ([`Document::locked_artboards`]). pub struct LockedArtboards<'a> { pub(crate) rects: Vec, diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 69ad127819..ce20d29cd8 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; use vectorcraft_geom::kurbo::ParamCurveArclen; -use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, SubPath, Vec2}; +use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; @@ -196,7 +196,11 @@ pub fn lerp_paint(a: &Paint, b: &Paint, t: f32) -> Paint { /// so dashes open out of a solid line; patterns of different lengths repeat to a common one. fn lerp_dash(x: Option<&Dash>, y: Option<&Dash>, t: f64) -> Option { let solid_like = |d: &Dash| Dash { - pattern: d.pattern.chunks(2).flat_map(|c| [c.iter().sum::(), 0.0]).take(d.pattern.len().max(2)).collect(), + // An odd pattern repeats twice per period, so pair up the doubled one to keep every gap closed. + pattern: if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() } + .chunks(2) + .flat_map(|c| [c.iter().sum::(), 0.0]) + .collect(), offset: d.offset, align_corners: d.align_corners, }; @@ -1025,6 +1029,27 @@ impl Rail { } } +/// A box round everything a blend of `keys` can paint once [`Rail::place`] puts its keys and steps +/// on its spine, turned to it with Align to Path: the spine's box grown by three times the farthest +/// any key paints from its centre. A step's shape lies within that distance of the point on the +/// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing +/// moves. +pub(crate) fn rail_reach(keys: &[Arc], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option { + if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath { + return None; + } + let spine = blend_spine(keys, spec)?.0.bounds()?; + let radius = keys + .iter() + .filter_map(|k| { + let (c, b) = (center_of(k), k.visual(symbols)?); + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; + Some(corners.into_iter().map(|q| (q - c).hypot()).fold(0.0, f64::max)) + }) + .fold(0.0, f64::max); + Some(spine.inflate(3.0 * radius, 3.0 * radius)) +} + // ===================================================================================== // Blend evaluation // ===================================================================================== @@ -1423,6 +1448,12 @@ mod tests { assert_eq!(p.at(0.5), (1.0, 1.0)); } + #[test] + fn odd_dash_blends_to_solid_with_closed_gaps() { + let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); + assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern); + } + #[test] fn copied_steps_get_new_members() { let rect = |x: f64| Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default())); diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index cfaad0a943..3915b239ed 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -125,7 +125,7 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { } /// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too. -fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { +pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { if !is_tiff(bytes) || oversized_tiff(bytes).is_some() { return None; } diff --git a/crates/doc/src/compound_shape.rs b/crates/doc/src/compound_shape.rs new file mode 100644 index 0000000000..3b36ff86dd --- /dev/null +++ b/crates/doc/src/compound_shape.rs @@ -0,0 +1,76 @@ +//! Compound shapes (Pathfinder panel › Make Compound Shape): a group whose members each have a +//! shape mode. It draws as the one area the modes make, from the backmost member up, painted with +//! the group's own appearance; the members stay editable. Evaluated in `vectorcraft-effects`. + +use serde::{Deserialize, Deserializer, Serialize}; + +use crate::{Node, NodeKind}; + +/// How a compound shape's member combines with the area of the members below it. The backmost +/// member's mode does not matter: it starts the area. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ShapeMode { + /// Adds the member's area. + #[default] + Add, + /// Takes the member's area away. + Subtract, + /// Keeps only what the member's area overlaps. + Intersect, + /// Keeps where exactly one of the area and the member's area is. + Exclude, +} + +impl ShapeMode { + /// Every mode, in the Pathfinder panel's order. + pub const ALL: [ShapeMode; 4] = [ShapeMode::Add, ShapeMode::Subtract, ShapeMode::Intersect, ShapeMode::Exclude]; + + /// The mode's name in commands and files. + pub fn name(self) -> &'static str { + match self { + ShapeMode::Add => "add", + ShapeMode::Subtract => "subtract", + ShapeMode::Intersect => "intersect", + ShapeMode::Exclude => "exclude", + } + } + + /// The mode named `s` ([`ShapeMode::name`]). + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.name() == s) + } +} + +/// Files are untrusted: a mode that isn't one of the names reads as Add. +impl<'de> Deserialize<'de> for ShapeMode { + fn deserialize>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(v.as_str().and_then(ShapeMode::parse).unwrap_or_default()) + } +} + +impl Node { + /// Is this a compound shape? Only a group that doesn't clip can be one: the mark on anything + /// else (from a file) is ignored. + pub fn is_compound_shape(&self) -> bool { + matches!(self.kind, NodeKind::Group { clip: false, .. }) && self.extras().compound_shape + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modes_read_back_and_unknown_ones_are_add() { + for m in ShapeMode::ALL { + let v = serde_json::to_value(m).unwrap(); + assert_eq!(v, serde_json::json!(m.name())); + assert_eq!(serde_json::from_value::(v).unwrap(), m); + } + for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] { + assert_eq!(serde_json::from_value::(v).unwrap(), ShapeMode::Add); + } + } +} diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index 8e4f807282..6f10da9b7a 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -485,7 +485,7 @@ mod tests { #[test] fn symbols_and_patterns_are_limited_too() { let mut d = Document::new(10.0, 10.0); - d.symbols.push(crate::Symbol { name: "s".into(), art: nested(MAX_DEPTH + 3) }); + d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: nested(MAX_DEPTH + 3) }); assert!(d.too_deep(None)); assert!(d.limit_depth()); assert!(!d.too_deep(None)); @@ -504,7 +504,7 @@ mod tests { for _ in 0..levels { art = Arc::new(Node::group(NodeId(3), vec![art])); } - d.symbols.push(crate::Symbol { name: format!("s{i}"), art }); + d.symbols.push(crate::Symbol { dynamic: false, name: format!("s{i}"), art }); } d } @@ -573,7 +573,7 @@ mod tests { }; let through_a_symbol = |d: &mut Document| { d.patterns.push(crate::PatternDef::new("p", vec![instance(2, "s")])); - d.symbols.push(crate::Symbol { name: "s".into(), art: painted(3, "p") }); + d.symbols.push(crate::Symbol { dynamic: false, name: "s".into(), art: painted(3, "p") }); }; for make in [&itself as &dyn Fn(&mut Document), &each_other, &through_a_symbol] { let mut d = doc(painted(1, "p")); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 478e54ca81..976d48485f 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -47,6 +47,7 @@ impl Document { patterns, pattern_edit, mask_edit, + symbol_edit, next_id: _, unknown, page_isolate, @@ -113,6 +114,7 @@ impl Document { (a, b) => a.is_none() && b.is_none(), } && *mask_edit == other.mask_edit + && *symbol_edit == other.symbol_edit && *unknown == other.unknown && *page_isolate == other.page_isolate && *page_knockout == other.page_knockout @@ -221,6 +223,7 @@ impl Document { patterns: vec![], pattern_edit: None, mask_edit: None, + symbol_edit: None, next_id: 1, unknown: Default::default(), page_isolate: false, diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c0c85b124e..b52e850c76 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -98,18 +98,22 @@ impl Document { self.views = kept; } - /// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the - /// mask already holds (the engine syncs it after every edit). + /// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working + /// copy of art the mask or the symbol already holds (the engine syncs it after every edit). pub fn drop_edit_modes(&mut self) { if let Some(me) = self.mask_edit.take() { self.layers.retain(|l| l.id != me.layer); } + if let Some(se) = self.symbol_edit.take() { + self.layers.retain(|l| l.id != se.layer); + } } - /// The document as saved and exported: without the opacity-mask editing layer. Borrowed when - /// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.) + /// The document as saved and exported: without the opacity-mask or symbol editing layer. + /// Borrowed when neither mode is on. (Pattern editing is saved: its tile layer holds unapplied + /// edits.) pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> { - if self.mask_edit.is_none() { + if self.mask_edit.is_none() && self.symbol_edit.is_none() { return std::borrow::Cow::Borrowed(self); } let mut d = self.clone(); diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 8379858745..d20c1ffe4e 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1,7 +1,9 @@ //! Hit testing over the document tree. +use std::cell::RefCell; use std::collections::HashSet; -use std::sync::OnceLock; +use std::rc::Rc; +use std::sync::{Arc, OnceLock}; use vectorcraft_geom::hit::{fill_contains, stroke_contains}; use vectorcraft_geom::{BezPath, FillRule, Point, Rect}; @@ -99,6 +101,128 @@ pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n)) } +/// One level of evaluation of a live object in a document, as the canvas draws it: type in an +/// envelope as its distorted glyph outlines, symbol instances as their art. Effects are evaluated +/// above this crate, so the engine registers one with [`set_live_art`]. It reads the object, the +/// document's symbols and patterns, and what [`LiveInputs`] stands for, and nothing else. +pub type LiveArt = fn(Option<&Document>, &Node) -> Vec; + +/// A number that changes whenever something outside the document that [`LiveArt`] reads changes, +/// such as the installed fonts or the plug-ins. +pub type LiveInputs = fn() -> u64; + +static LIVE_ART: OnceLock<(LiveArt, LiveInputs)> = OnceLock::new(); + +/// Register how a live object's art is evaluated for clicks, and the number that changes with what +/// else it reads (the first registration stays). +pub fn set_live_art(f: LiveArt, inputs: LiveInputs) { + // Already set: the same engine, registered by another session. + let _ = LIVE_ART.set((f, inputs)); +} + +/// The registered [`LiveInputs`] now, 0 while nothing is registered. +fn live_inputs() -> u64 { + LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) +} + +/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by +/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`]. +struct EvaluatedLive { + node: Node, + symbols: Vec<(String, Arc)>, + patterns: Vec, + inputs: u64, + art: Rc>, + size: usize, +} + +impl EvaluatedLive { + /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? + fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { + self.inputs == inputs + && self.symbols.len() == doc.symbols.len() + && self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art)) + && self.node == *n + && self.patterns == doc.patterns + } +} + +/// How many evaluations [`live_art`] keeps on each thread: the pointer moving in a blend's or an +/// envelope's stroke band hits it again and again, and an envelope can hold a blend. +const LIVE_KEPT: usize = 4; + +/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than +/// this is not kept. +const LIVE_KEPT_SIZE: usize = 250_000; + +/// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths. +fn art_size(art: &[Node]) -> usize { + let mut size = 0usize; + for n in art { + n.walk(&mut |c| size = size.saturating_add(1 + c.path_data().map_or(0, |p| p.anchor_count()))); + } + size +} + +/// Does `n`, or the art of a symbol or a pattern of `doc`, hold a placed document? Its art changes +/// when the file is read, so [`live_art`] does not keep an evaluation of `n`. +fn holds_placed(doc: &Document, n: &Node) -> bool { + let mut placed = false; + let mut find = |c: &Node| placed |= matches!(c.kind, NodeKind::PlacedDocument(_)); + n.walk(&mut find); + doc.symbols.iter().for_each(|s| s.art.walk(&mut find)); + doc.patterns.iter().flat_map(|p| &p.art).for_each(|a| a.walk(&mut find)); + placed +} + +thread_local! { + /// The evaluations [`live_art`] keeps, the latest first. + static EVALUATED: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while +/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of +/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's +/// symbols or patterns hold a placed document ([`holds_placed`]). +fn live_art(doc: &Document, n: &Node) -> Rc> { + let inputs = live_inputs(); + let kept = EVALUATED.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; + let e = kept.remove(i); + let art = e.art.clone(); + kept.insert(0, e); + Some(art) + }); + if let Some(art) = kept { + return art; + } + #[cfg(test)] + LIVE_EVALUATED.with(|c| c.set(c.get() + 1)); + let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n))); + let size = art_size(&art); + if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { + return art; + } + let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); + let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size }; + EVALUATED.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(LIVE_KEPT); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); + art +} + +#[cfg(test)] +thread_local! { + /// How many live objects [`live_art`] evaluated on this thread. + static LIVE_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Topmost editable object under `p`. pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option { hit_test_skipping(doc, p, opt, &|_| false, true) @@ -110,6 +234,12 @@ pub fn hit_test_visible(doc: &Document, p: Point, opt: HitOptions) -> Option bool) -> Option { + hit_test_skipping(doc, p, opt, skip, false) +} + /// The object of `selected` (topmost first) whose own art lies under `p` where a clipping mask /// hides it: a clip group (or a layer with a clipping mask) holding it doesn't clip to `p`. A /// click there hits nothing ([`hit_test`]), so the selection tools grab the selection by that @@ -538,20 +668,15 @@ fn hit_children( } /// The order a click at `p` tries the children of `parent` in, front first: their stacking order -/// from the top, except that in an Intertwine group the members drawn over the others at `p` -/// come first (from the top among them too). +/// from the top, except that in an Intertwine group the members are tried in the order they are +/// drawn at `p`, from the top ([`crate::intertwine::tier_at`]). fn hit_order<'a>(parent: &Node, children: &'a [std::sync::Arc], p: Point) -> impl Iterator + 'a { - let over: Vec = if matches!(parent.kind, NodeKind::Intertwine { .. }) { - let contains = |a: &vectorcraft_geom::PathData| fill_contains(&a.to_bezpath(), vectorcraft_geom::FillRule::NonZero, p); - (0..children.len()).rev().filter(|i| children.get(*i).and_then(|c| crate::intertwine::over_area(c)).is_some_and(contains)).collect() - } else { - vec![] - }; - let rest = (0..children.len()).rev().filter({ - let over = over.clone(); - move |i| !over.contains(i) - }); - over.into_iter().chain(rest) + let mut order: Vec = (0..children.len()).rev().collect(); + if matches!(parent.kind, NodeKind::Intertwine { .. }) { + let tier = |i: usize| children.get(i).map_or(0, |c| crate::intertwine::tier_at(c, p)); + order.sort_by_cached_key(|i| std::cmp::Reverse((tier(*i), *i))); + } + order.into_iter() } /// A click on the strokes of a path or compound path `n` along `bp`: what any visible stroke @@ -564,7 +689,15 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } +#[cfg(test)] +thread_local! { + /// How many objects [`hit_leaf`] tested on this thread. + static LEAVES_TESTED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + #[cfg(test)] + LEAVES_TESTED.with(|c| c.set(c.get() + 1)); match &n.kind { NodeKind::Path { path, rule, .. } => { let bp = path.to_bezpath(); @@ -611,9 +744,18 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), }) } - NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } => { + NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } + // A blend or an envelope is hit within its bounds, and outside them where its evaluated + // art paints: a blend's keys and steps on a spine can reach past the keys and the spine, + // and the strokes of an envelope's distorted contents past its bounds. + NodeKind::Blend { .. } | NodeKind::Envelope { .. } => { + if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + return Some(HitKind::Bounds); + } + live_art(symbols.document(), n).iter().find_map(|g| hit_any(g, p, opt, symbols)) + } NodeKind::Repeat(r) => r.expand(Some(symbols.document())).iter().find_map(|g| hit_any(g, p, opt, symbols)), NodeKind::Mesh(m) => { let bp = m.outline().to_bezpath(); @@ -650,8 +792,25 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool { /// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + // Hidden art does not hit. + if !n.visible { + return None; + } + // Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are + // passed by without being measured. + if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) { + return None; + } match &n.kind { - NodeKind::Group { children, .. } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)), + // A clip group only hits inside its clipping path. + NodeKind::Group { children, clip } => { + if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) { + return None; + } + children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) + } + // An intertwine group hits by its members, as on the canvas. + NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)), _ => hit_leaf(n, p, opt, symbols), } } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 08503e8a77..c4d6c565e0 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -429,6 +429,151 @@ fn a_marquee_meets_blends_and_envelopes_by_their_box() { } } +/// A click just outside a blend's bounds, in the reach of its keys' strokes, tests only the steps +/// whose own reach holds the point, not every step of the evaluated blend. +#[test] +fn a_click_in_a_blends_stroke_band_tests_only_the_steps_that_reach_it() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + // 10 pt circles with 4 pt strokes, y 295 to 305, from x 10 to x 890: 200 steps about 4.3 pt apart. + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone())); + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let count = |p: Point| { + LEAVES_TESTED.with(|c| c.set(0)); + let h = hit_test(&d, p, HitOptions::default()).map(|h| h.leaf); + (h, LEAVES_TESTED.with(std::cell::Cell::get)) + }; + // On the steps' strokes halfway between the keys, 4 pt above the bounds: a few steps reach it. + let (h, tested) = count(Point::new(450.0, 291.0)); + assert_eq!(h, Some(blend)); + assert!(tested < 20, "{tested} objects tested"); + // In the corner of the reach, outside every stroke: nothing hits. + let (h, tested) = count(Point::new(6.0, 291.0)); + assert_eq!(h, None); + assert!(tested < 20, "{tested} objects tested"); +} + +/// An intertwine group in a live object's evaluated art (a blend key a spine moves) hits by its +/// members. +#[test] +fn evaluated_art_hits_an_intertwine_group_by_its_members() { + let d = Document::new(200.0, 200.0); + let square = Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art())); + let group = Node::new(NodeId(8), NodeKind::Intertwine { children: vec![square] }); + let symbols = d.symbol_boxes(); + assert_eq!(hit_any(&group, Point::new(10.0, 10.0), HitOptions::default(), &symbols), Some(HitKind::Fill)); + assert_eq!(hit_any(&group, Point::new(50.0, 50.0), HitOptions::default(), &symbols), None); +} + +/// The pointer moving in a blend's stroke band evaluates the blend once, and again after the blend +/// or a symbol of the document changes. +#[test] +fn clicks_in_a_blends_stroke_band_evaluate_it_once_until_it_changes() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone())); + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + for x in [448.0, 450.0, 452.0] { + assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + } + assert_eq!(evaluated(), before + 1); + // 100 steps 8.7 pt apart: a step still reaches (450, 291). + if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(blend).map(|n| &mut n.kind) { + spec.spacing = crate::live::BlendSpacing::Steps(100); + } + assert_eq!(hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + assert_eq!(evaluated(), before + 2); + let art = circle(d.alloc_id(), 0.0); + d.symbols.push(crate::Symbol { dynamic: false, name: "dot".into(), art }); + hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()); + assert_eq!(evaluated(), before + 3); + hit_test(&d, Point::new(450.0, 291.0), HitOptions::default()); + assert_eq!(evaluated(), before + 3); +} + +/// Evaluated art larger than [`LIVE_KEPT_SIZE`] is not kept: each click in the blend's stroke band +/// evaluates it again. +#[test] +fn evaluated_art_past_the_kept_size_is_not_kept() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + // A 10 pt circle drawn with 2,000 anchors: 202 objects of 2,000 anchors each with 200 steps. + let circle = |id, x: f64| { + let points: Vec = (0..2000) + .map(|i| { + let a = f64::from(i) * std::f64::consts::TAU / 2000.0; + Point::new(x + 5.0 + 5.0 * a.cos(), 300.0 + 5.0 * a.sin()) + }) + .collect(); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + Arc::new(Node::path(id, path, stroked.clone())) + }; + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + for x in [448.0, 450.0] { + assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + } + assert_eq!(evaluated(), before + 2); +} + +/// While the document's symbols hold a placed document, whose art changes when its file is read, +/// each click in a blend's stroke band evaluates the blend again. +#[test] +fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let stroked = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0); + let circle = |id, x: f64| Arc::new(Node::path(id, shapes::ellipse(Rect::new(x, 295.0, x + 10.0, 305.0)), stroked.clone())); + let blend = d.alloc_id(); + let keys = vec![circle(d.alloc_id(), 10.0), circle(d.alloc_id(), 880.0)]; + let spec = crate::live::BlendSpec { spacing: crate::live::BlendSpacing::Steps(200), ..Default::default() }; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Box::new(spec) })).unwrap(); + let placed = crate::PlacedDocument { + link: crate::LinkInfo::new("/art/logo.vectorcraft"), + key: "logo".into(), + bounding: false, + page_box: crate::PageBox::Crop, + width: 80.0, + height: 40.0, + xf: vectorcraft_geom::Affine::IDENTITY, + placement: Default::default(), + }; + let art = Arc::new(Node::new(d.alloc_id(), NodeKind::PlacedDocument(Box::new(placed)))); + d.symbols.push(crate::Symbol { dynamic: false, name: "logo".into(), art }); + let evaluated = || LIVE_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + for x in [448.0, 450.0] { + assert_eq!(hit_test(&d, Point::new(x, 291.0), HitOptions::default()).map(|h| h.leaf), Some(blend)); + } + assert_eq!(evaluated(), before + 2); +} + +/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins +/// ([`LiveInputs`]) are as they were. +#[test] +fn a_kept_evaluation_is_stale_after_the_live_inputs_change() { + let d = Document::new(100.0, 100.0); + let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 }; + assert!(e.is_of(&d, &n, 7)); + assert!(!e.is_of(&d, &n, 8)); +} + /// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a /// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the /// clipping path and the art. @@ -841,7 +986,7 @@ fn objects_at_matches_repeated_hits_on_random_documents() { fn objects_at_finds_symbol_instances_by_their_art() { let mut d = Document::new(200.0, 200.0); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art()); - d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) }); + d.symbols.push(crate::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); let instance = |id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) }); d.insert(Some(layer), 0, instance(top, 0.0)).unwrap(); diff --git a/crates/doc/src/inks.rs b/crates/doc/src/inks.rs index 8235dc4d20..696b274134 100644 --- a/crates/doc/src/inks.rs +++ b/crates/doc/src/inks.rs @@ -109,9 +109,9 @@ fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) { } } -/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, not -/// opacity masks) with its swatch link and tint. Mesh points have no link: changes to it are -/// dropped. +/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an +/// image's colorize color, not opacity masks) with its swatch link and tint. Mesh points have no +/// link: changes to it are dropped. pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) { for it in &mut n.appearance.items { match it { @@ -119,6 +119,9 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) { AppearanceItem::Stroke(l) => visit_paint(&mut l.paint, f), } } + if let Some(p) = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()) { + visit_paint(p, f); + } match &mut n.kind { NodeKind::Text(t) => { for r in &mut t.runs { diff --git a/crates/doc/src/intertwine.rs b/crates/doc/src/intertwine.rs index e22ccbbaf3..8a6ab6786f 100644 --- a/crates/doc/src/intertwine.rs +++ b/crates/doc/src/intertwine.rs @@ -1,36 +1,51 @@ //! Object › Intertwine: objects that pass over and under each other. //! //! An Intertwine group ([`NodeKind::Intertwine`]) keeps its members as they are, in their own -//! stacking order. A member can be drawn over the other members in part of the group: that area -//! is the member's [`crate::node::NodeExtras::intertwine`], in document coordinates. The group -//! draws (and exports, and is hit) as its live expansion ([`expand`]): the members, then, for -//! each member with an area, a copy of it clipped to that area. Where several members are drawn -//! over the others in one place, the upper one in the stacking order ends on top. +//! stacking order. A member can be drawn over other members in part of the group, at a tier: the +//! area of tier 1 is the member's [`crate::node::NodeExtras::intertwine`], and the areas of tiers 2 +//! and up are its [`crate::node::NodeExtras::intertwine_tiers`], in document coordinates. In each +//! place the members are drawn by their tier there (0 outside their areas), and members of one +//! tier in their stacking order, so any order of the members can be set for each overlap area. +//! The group draws (and exports, and is hit) as its live expansion ([`expand`]): the members, +//! then, tier by tier, a copy of each member with an area of that tier clipped to it. //! //! The members stay editable, and Release gives them back as they were (the areas let go). //! Behaviour: . use std::sync::Arc; -use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{FillRule, PathData, Point}; use crate::{Node, NodeId, NodeKind}; -/// The area where `n` is drawn over the other members of its Intertwine group (empty: nowhere). -pub fn over_area(n: &Node) -> Option<&PathData> { - n.extras().intertwine.as_deref().filter(|a| !a.is_empty()) +/// The areas where `n` is drawn over other members of its Intertwine group, each with its tier +/// (1 and up); empty ones are left out. +pub fn tier_areas(n: &Node) -> impl Iterator { + let e = n.extras(); + e.intertwine + .as_deref() + .map(|a| (1, a)) + .into_iter() + .chain(e.intertwine_tiers.iter().enumerate().map(|(k, a)| (k + 2, a))) + .filter(|(_, a)| !a.is_empty()) } -/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then each -/// member with an area drawn over the others, as a clip group of that area around a copy of it -/// (ids 0: generated art). +/// The tier `n` is drawn at at `p`: the highest tier whose area holds `p` (0: none does). +pub fn tier_at(n: &Node, p: Point) -> usize { + tier_areas(n).filter(|(_, a)| fill_contains(&a.to_bezpath(), FillRule::NonZero, p)).map(|(t, _)| t).max().unwrap_or(0) +} + +/// The members of an Intertwine group evaluated as plain art: the members (ids kept), then, for +/// each tier from 1 up, each member with an area of that tier, as a clip group of that area +/// around a copy of it (ids 0: generated art). pub fn expand(children: &[Arc]) -> Vec { let mut out: Vec = children.iter().map(|c| plain(c)).collect(); - for c in children { - let Some(area) = over_area(c) else { continue }; - if !c.visible { - continue; - } + let mut over: Vec<(usize, usize, &PathData)> = + children.iter().enumerate().filter(|(_, c)| c.visible).flat_map(|(i, c)| tier_areas(c).map(move |(t, a)| (t, i, a))).collect(); + over.sort_by_key(|(t, i, _)| (*t, *i)); + for (_, i, area) in over { + let Some(c) = children.get(i) else { continue }; let mut clip = Node::new(NodeId(0), NodeKind::Path { path: area.clone(), rule: FillRule::NonZero, live: None, clipping: true, guide: false }); clip.appearance = crate::Appearance::default().into(); let mut copy = plain(c); @@ -40,11 +55,13 @@ pub fn expand(children: &[Arc]) -> Vec { out } -/// `n` without its Intertwine area (the expansion is plain art). +/// `n` without its Intertwine areas (the expansion is plain art). fn plain(n: &Node) -> Node { let mut n = n.clone(); - if n.extras().intertwine.is_some() { - n.extras_mut().intertwine = None; + if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() { + let mut e = n.extras_mut(); + e.intertwine = None; + e.intertwine_tiers = Vec::new(); } n } @@ -88,6 +105,28 @@ mod tests { assert_eq!((out[2].id, children[1].id), (NodeId(0), NodeId(0)), "generated art has no ids of its own"); } + #[test] + fn copies_are_drawn_tier_by_tier() { + let over = || shapes::rectangle(Rect::new(5.0, 0.0, 10.0, 10.0)); + // The lower member at tier 2, the upper one at tier 1: the lower one ends on top. + let mut a = (*square(1, 0.0)).clone(); + a.extras_mut().intertwine_tiers = vec![over()]; + let mut b = (*square(2, 5.0)).clone(); + b.extras_mut().intertwine = Some(Box::new(over())); + let kids = vec![Arc::new(a), Arc::new(b)]; + assert_eq!((tier_at(&kids[0], Point::new(7.0, 5.0)), tier_at(&kids[1], Point::new(7.0, 5.0))), (2, 1)); + assert_eq!(tier_at(&kids[0], Point::new(2.0, 5.0)), 0); + let out = expand(&kids); + assert_eq!(out.len(), 4, "both members, then the copy of tier 1, then the one of tier 2"); + assert!(out.iter().all(|n| n.extras().intertwine.is_none() && n.extras().intertwine_tiers.is_empty()), "the expansion is plain art"); + let copied = |n: &Node| match &n.kind { + NodeKind::Group { children, clip: true } => children[1].path_data().cloned(), + k => panic!("a clip group: {k:?}"), + }; + assert_eq!(copied(&out[2]).as_ref(), kids[1].path_data()); + assert_eq!(copied(&out[3]).as_ref(), kids[0].path_data()); + } + #[test] fn a_hidden_member_is_not_drawn_over_the_others() { let mut a = (*square(1, 0.0)).clone(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 91ede3df9d..b742a1dd75 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -11,6 +11,7 @@ pub mod blend; pub mod cancel; pub mod clipnest; pub mod cmyk; +pub mod compound_shape; pub mod corners; pub mod depth; pub mod dimension; @@ -23,11 +24,13 @@ pub mod intertwine; pub mod shared; mod symbol_export_type; mod symbol_nine_slice; +pub mod symbol_overrides; mod symbol_registration; pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{SYMBOL_NINE_SLICE, SymbolNineSlice}; +pub use symbol_overrides::SymbolOverride; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; pub mod links; pub mod live; @@ -42,7 +45,7 @@ pub mod overprint; pub mod pattern; pub mod perspective; mod pixels; -pub use pixels::MAX_RASTER_ALLOC; +pub use pixels::{GraySource, MAX_RASTER_ALLOC}; pub mod placed_document; pub mod plugin_data; pub mod profiles; @@ -76,6 +79,7 @@ pub use appearance::{ StrokeAlign, StrokeLayer, WidthProfile, }; pub use assets::ExportAsset; +pub use compound_shape::ShapeMode; pub use corners::LiveCorners; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ @@ -102,10 +106,12 @@ pub use selection::{AnchorRef, SegmentRef, Selection}; pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes}; pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource}; pub use style_libs::StyleLibrary; +pub use text::FontHeightReference; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, - RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, + RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, + WrapShape, }; pub use trace::TraceView; pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables}; @@ -136,7 +142,7 @@ pub use guides::{GridPrefs, Guide, RulerMode}; #[cfg(test)] use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; -pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol}; +pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol, SymbolEdit}; pub use units::{ColorMode, Unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -216,6 +222,10 @@ pub struct Document { /// still read so files saved mid-edit by older versions load without the editing layer. #[serde(default, skip_serializing)] pub mask_edit: Option, + /// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the + /// symbol already holds the art of its editing layer. + #[serde(default, skip_serializing)] + pub symbol_edit: Option, next_id: u64, /// Foreign data preserved on round-trip. #[serde(default, skip_serializing_if = "skip::is_empty_map")] diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 650361374c..9a2aa4fea5 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -63,7 +63,7 @@ pub use expand::{ }; #[cfg(test)] use mesh::grid_eval; -pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; +pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; pub use warp::{WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, warp_point}; #[cfg(test)] @@ -181,6 +181,44 @@ mod tests { assert!((p.x - 37.0).abs() < 1e-6 && (p.y - 81.0).abs() < 1e-6, "{p:?}"); } + /// #3592: a mesh read from a file can have any number of patches, and the view any zoom, so the + /// quads one tessellation makes are budgeted: the subdivision per patch gives way before memory + /// does, and each patch stays at least one quad. + #[test] + fn a_large_mesh_tessellates_within_the_quad_budget() { + let mesh = |n: u32| GradientMesh::from_surface(n, n, &|u, v| Point::new(u * 300.0, v * 300.0), &|u, v| Color::rgb(u as f32, v as f32, 0.5)); + // 3,600 patches at 32 x 32 would be 3.7 million quads. + let m = mesh(60); + let quads = m.quads(32); + assert!(quads.len() <= GradientMesh::MAX_QUADS, "{} quads", quads.len()); + assert!(quads.len() >= 3600 * 4, "still finer than a quad per patch: {}", quads.len()); + // A small mesh keeps the subdivision asked for. + assert_eq!(mesh(3).quads(8).len(), 9 * 64); + // The finest the view asks for, on a mesh of 22,500 patches, is a few quads per patch. + let big = mesh(150).quads(64); + assert!(big.len() <= GradientMesh::MAX_QUADS && big.len() >= 22_500, "{} quads", big.len()); + // More patches than the budget has quads is malformed, as a point count that doesn't fit is. + let point = MeshPoint { p: Point::ZERO, color: Color::rgb(0.0, 0.0, 0.0), opacity: 1.0, handles: [Vec2::ZERO; 4] }; + let huge = GradientMesh { rows: 2000, cols: 2000, points: vec![point; 2001 * 2001] }; + assert!(!huge.is_valid()); + assert!(huge.quads(1).is_empty()); + } + + /// Flat pieces of a mesh over the quad budget follow the coarser subdivision [`GradientMesh::quads`] + /// gives way to: each patch's pieces are its own quads', so together they cover the mesh once. + #[test] + fn a_large_meshs_pieces_follow_the_quad_budget() { + let m = GradientMesh::from_surface(60, 60, &|u, v| Point::new(u * 300.0, v * 300.0), &|u, v| Color::rgb(u as f32, v as f32, 0.5)); + let area = |pts: &[Point]| { + let n = pts.len(); + (0..n).map(|i| pts[i].x * pts[(i + 1) % n].y - pts[(i + 1) % n].x * pts[i].y).sum::().abs() / 2.0 + }; + let pieces = m.pieces(32); + assert!(pieces.len() >= 3600, "{} pieces", pieces.len()); + let total: f64 = pieces.iter().map(|p| area(&p.pts)).sum(); + assert!((total - 90_000.0).abs() < 90.0, "covered {total}"); + } + /// 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] @@ -195,17 +233,86 @@ mod tests { assert_eq!(envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 100.0))(p), p); } + /// How far the border of `m` strays from the ellipse in `r`, in points (measured across the + /// ellipse's short radius), checked at 20 places along every border edge. + fn mesh_border_off_ellipse(m: &GradientMesh, r: Rect) -> f64 { + let (rows, cols) = (m.rows as usize, m.cols as usize); + let edges = (0..cols).flat_map(|c| [m.edge_u(0, c), m.edge_u(rows, c)]).chain((0..rows).flat_map(|k| [m.edge_v(k, 0), m.edge_v(k, cols)])); + let (c, a, b) = (r.center(), r.width() / 2.0, r.height() / 2.0); + edges + .flat_map(|e| (0..=20).map(move |i| e.eval(f64::from(i) / 20.0))) + .map(|p| ((p.x - c.x) / a).hypot((p.y - c.y) / b) - 1.0) + .fold(0.0f64, |w, d| w.max(d.abs() * a.min(b))) + } + + /// #3187: a gradient mesh made from an ellipse keeps the ellipse's shape: a Mesh tool click + /// (a 1×1 mesh with lines through the point) and Create Gradient Mesh's 4×4 grid both lay + /// their border on the outline, within about twice the 0.35 pt the outline is flattened to. + /// The 1×1 mesh was up to 7 pt off this 400 × 300 pt ellipse. + #[test] + fn a_mesh_from_an_ellipse_keeps_its_outline() { + const OFF: f64 = 0.75; + let r = Rect::new(100.0, 100.0, 500.0, 400.0); + let e = shapes::ellipse(r); + for (rows, cols) in [(1, 1), (4, 4), (2, 5)] { + let m = GradientMesh::for_path(&e, rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let off = mesh_border_off_ellipse(&m, r); + assert!(off < OFF, "{rows}×{cols} mesh: border {off} pt off the ellipse"); + } + let made = GradientMesh::for_path(&e, 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let mut m = made.clone(); + // Off centre, so each line splits its edges unevenly. + let i = m.add_lines_at(Point::new(200.0, 330.0), 0.0).unwrap(); + let off = mesh_border_off_ellipse(&m, r); + assert!(off < OFF, "after a Mesh tool click: {off} pt"); + // Deleting the lines again (Alt-click) gives the border back as it was. + assert!(m.remove_point_lines(i)); + assert_eq!((m.rows, m.cols), (1, 1)); + for (k, (now, was)) in m.points.iter().zip(&made.points).enumerate() { + let moved = now.handles.iter().zip(&was.handles).map(|(a, b)| (*a - *b).hypot()).fold(0.0, f64::max); + assert!(now.p.distance(was.p) < 1e-6 && moved < 1e-3, "point {k}: {now:?}, made as {was:?}"); + } + // With a handle at the new border point shortened since, the two edges no longer make one + // curve: the merged edge is straight rather than grown past its ends. + let mut m = made.clone(); + let i = m.add_lines_at(Point::new(200.0, 330.0), 0.0).unwrap(); + let top = m.idx(0, 1); + m.points[top].handles[H_LEFT] *= 1e-4; + assert!(m.remove_point_lines(i)); + let (a, b) = (m.points[0].p, m.points[1].p); + assert!((m.points[0].handles[H_RIGHT] - (b - a) / 3.0).hypot() < 1e-9, "{:?}", m.points[0].handles); + // A rectangle's mesh keeps straight edges with handles a third of the way along. + let m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 60.0)), 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let e = m.edge_u(0, 0); + assert!(e.p1.distance(Point::new(30.0, 0.0)) < 1e-6 && e.p2.distance(Point::new(60.0, 0.0)) < 1e-6, "{e:?}"); + } + #[test] fn mesh_insert_and_remove_lines() { let mut m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 1, 1, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); - let i = m.add_lines_at(Point::new(30.0, 60.0)).unwrap(); + let i = m.add_lines_at(Point::new(30.0, 60.0), 0.0).unwrap(); assert_eq!((m.rows, m.cols), (2, 2)); assert!(m.points[i].p.distance(Point::new(30.0, 60.0)) < 0.5, "{:?}", m.points[i].p); assert!(m.remove_point_lines(i)); assert_eq!((m.rows, m.cols), (1, 1)); } + /// A point outside the mesh within the tolerance locates the nearest point of its edge. + #[test] + fn mesh_locate_within_reaches_the_edge() { + let m = GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), 2, 2, Color::BLACK, MeshAppearance::Flat, 0.0).unwrap(); + let p = Point::new(102.0, 30.0); + assert_eq!(m.locate(p), None); + assert_eq!(m.locate_within(p, 1.0), None); + let (r, c, u, v) = m.locate_within(p, 3.0).unwrap(); + assert_eq!((r, c), (0, 1)); + assert_eq!(u, 1.0, "on the right edge"); + let q = m.eval(r, c, u, v); + assert!(q.distance(Point::new(100.0, 30.0)) < 1e-6, "{q:?}"); + assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0))); + } + /// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB. #[test] fn a_cmyk_mesh_mixes_its_inks() { @@ -221,6 +328,25 @@ mod tests { assert!(matches!(m.color_at(0, 0, 0.5, 0.5).0, Color::Rgb { .. })); } + /// #3232: the Appearance highlight lightens each point towards white in its own model, so a + /// CMYK mesh stays CMYK (K shrinks with the other inks) and a grey one stays grey. + #[test] + fn mesh_highlight_keeps_each_points_model() { + let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let ink = Color::Cmyk { c: 0.0, m: 0.4, y: 0.6, k: 0.1 }; + let m = GradientMesh::for_path(&square, 2, 2, ink, MeshAppearance::ToCenter, 50.0).unwrap(); + assert_eq!(m.points[0].color, ink, "corners stay"); + let centre = m.points[m.idx(1, 1)].color; + let Color::Cmyk { c, m: mg, y, k } = centre else { panic!("{centre:?}") }; + assert!(c.abs() < 1e-6 && (mg - 0.2).abs() < 1e-6 && (y - 0.3).abs() < 1e-6 && (k - 0.05).abs() < 1e-6, "{c} {mg} {y} {k}"); + assert!(matches!(m.color_at(0, 0, 0.5, 0.5).0, Color::Cmyk { .. }), "patches mix in CMYK"); + let m = GradientMesh::for_path(&square, 2, 2, Color::gray(0.8), MeshAppearance::ToEdge, 100.0).unwrap(); + assert_eq!((m.points[0].color, m.points[m.idx(1, 1)].color), (Color::gray(0.0), Color::gray(0.8))); + // RGB lightens in RGB as before. + let m = GradientMesh::for_path(&square, 2, 2, Color::rgb(1.0, 0.0, 0.0), MeshAppearance::ToCenter, 100.0).unwrap(); + assert_eq!(m.points[m.idx(1, 1)].color.to_hex(), "#ffffff"); + } + /// 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] diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index c67dbee3ee..66d20f27b6 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -293,9 +293,10 @@ pub fn is_live(n: &Node) -> bool { ) } -/// Mesh tessellation as filled quad paths (no stroke), `n`×`n` per patch. +/// Mesh tessellation as flat-filled paths (no stroke): each patch cut `n`×`n`, its quads joined +/// where the colour hardly changes ([`GradientMesh::pieces`]). pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec { - m.quads(n) + m.pieces(n) .into_iter() .map(|q| { let mut ap = Appearance::default(); diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs index 783e325562..a87cbd9b4f 100644 --- a/crates/doc/src/live/mesh.rs +++ b/crates/doc/src/live/mesh.rs @@ -35,6 +35,15 @@ pub struct MeshQuad { pub corners: [(Color, f32); 4], } +/// One flat-coloured piece of a mesh ([`GradientMesh::pieces`]): a closed outline through +/// tessellation points, its colour and opacity. +#[derive(Clone, Debug, PartialEq)] +pub struct MeshPiece { + pub pts: Vec, + pub color: Color, + pub opacity: f32, +} + /// Create Gradient Mesh → Appearance. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum MeshAppearance { @@ -157,6 +166,76 @@ impl Coons { // Gradient meshes // ===================================================================================== +/// The handles, as offsets from `ends`, of the cubic from `ends.0` to `ends.1` that comes closest +/// (least squares) to `side` between `span.0` and `span.1`; `None` when they can't be computed. +/// Each point of the side is matched to the curve's nearest point, refined over a few rounds. +fn fit_edge(side: &[Point], span: (f64, f64), ends: (Point, Point)) -> Option<(Vec2, Vec2)> { + const N: usize = 32; + const ROUNDS: usize = 6; + let (p0, p3) = (ends.0, ends.1); + let qs: Vec = (1..N).map(|i| Coons::sample(side, span.0 + (span.1 - span.0) * i as f64 / N as f64)).collect(); + let mut ts: Vec = (1..N).map(|i| i as f64 / N as f64).collect(); + let mut fit = None; + for _ in 0..ROUNDS { + let (mut c11, mut c12, mut c22) = (0.0, 0.0, 0.0); + let (mut x1, mut x2) = (Vec2::ZERO, Vec2::ZERO); + for (q, &t) in qs.iter().zip(&ts) { + let s = 1.0 - t; + let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t); + let r = q.to_vec2() - b0 * p0.to_vec2() - b3 * p3.to_vec2(); + c11 += b1 * b1; + c12 += b1 * b2; + c22 += b2 * b2; + x1 += b1 * r; + x2 += b2 * r; + } + let det = c11 * c22 - c12 * c12; + if det.abs() < 1e-12 { + break; + } + let (p1, p2) = (((c22 * x1 - c12 * x2) / det).to_point(), ((c11 * x2 - c12 * x1) / det).to_point()); + if !(p1.is_finite() && p2.is_finite()) { + break; + } + fit = Some((p1 - p0, p2 - p3)); + // One Newton step towards the nearest point of the curve for each point of the side. + let c = CubicBez::new(p0, p1, p2, p3); + let (a, b, k) = (p1 - p0, p2 - p1, p3 - p2); + for (q, t) in qs.iter().zip(ts.iter_mut()) { + let s = 1.0 - *t; + let v = 3.0 * (s * s * a + 2.0 * s * *t * b + *t * *t * k); + let acc = 6.0 * (s * (b - a) + *t * (k - b)); + let e = c.eval(*t) - *q; + let den = v.hypot2() + e.dot(acc); + if den.abs() > 1e-12 { + *t = (*t - e.dot(v) / den).clamp(0.0, 1.0); + } + } + } + fit +} + +/// The handles of one cubic standing for two edges that meet at point `mid.0`, whose handles +/// towards them are `mid.1` (towards `a`) and `mid.2` (towards `b`), as offsets from their outer +/// ends: each outer handle grown back by the share of the curve its edge had, which undoes the +/// split [`GradientMesh::insert_row`] and [`GradientMesh::insert_col`] make, so deleting a mesh +/// line keeps the curve of the border it crossed (#3187). The share is the split parameter, read +/// from the lengths of the middle handles. When the edges no longer fit one cubic (a point or a +/// handle was moved since the split), the cubic grown back would not pass through the middle +/// point, and the merged edge is straight. +fn merged_handles(a: (Point, Vec2), mid: (Point, Vec2, Vec2), b: (Point, Vec2)) -> (Vec2, Vec2) { + let straight = ((b.0 - a.0) / 3.0, (a.0 - b.0) / 3.0); + let (la, lb) = (mid.1.hypot(), mid.2.hypot()); + let t = la / (la + lb); + if !(0.01..=0.99).contains(&t) { + return straight; + } + let (ha, hb) = (a.1 / t, b.1 / (1.0 - t)); + let through = CubicBez::new(a.0, a.0 + ha, b.0 + hb, b.0).eval(t); + let tol = 1e-3 * (a.0.distance(mid.0) + mid.0.distance(b.0)).max(1e-9); + if ha.is_finite() && hb.is_finite() && through.distance(mid.0) <= tol { (ha, hb) } else { straight } +} + /// `0, 1/n, …, 1` for `n` (clamped to 1..=200) even steps. fn even_steps(n: u32) -> Vec { let n = n.clamp(1, 200); @@ -170,11 +249,22 @@ pub(super) fn grid_len(rows: u32, cols: u32) -> Option { } impl GradientMesh { + /// The most quads one tessellation ([`Self::quads`]) makes, and so the most patches a mesh can + /// have: about 170 bytes a quad, so about 170 MB. A file's mesh can have any number of patches + /// and the view any zoom; the subdivision per patch gives way before memory does, and a mesh + /// with more patches than that is malformed, like a point count that doesn't fit (#3592). + pub const MAX_QUADS: usize = 1 << 20; + 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 && grid_len(self.rows, self.cols) == Some(self.points.len()) + self.rows >= 1 && self.cols >= 1 && grid_len(self.rows, self.cols) == Some(self.points.len()) && self.patches() <= Self::MAX_QUADS + } + + /// The number of patches (rows times columns), saturating. + fn patches(&self) -> usize { + (self.rows as usize).saturating_mul(self.cols as usize) } /// A 1×1 mesh from its four corners (bottom-left, top-left, top-right, bottom-right in u/v @@ -263,11 +353,54 @@ impl GradientMesh { /// colour and opacity `color_at` gives at its position (a gradient fill's, say). pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option { let coons = Coons::from_path(path)?; - Some(Self::from_grid(&even_steps(cols), &even_steps(rows), &|u, v| coons.eval(u, v), &|_, _, p| color_at(p))) + let (us, vs) = (even_steps(cols), even_steps(rows)); + let mut m = Self::from_grid(&us, &vs, &|u, v| coons.eval(u, v), &|_, _, p| color_at(p)); + m.fit_border(&coons, &us, &vs); + Some(m) + } + + /// Give each edge on the mesh's border the handles that make it follow the outline it stands + /// for, in place of the handles [`Self::from_grid`] estimates from the surface's derivatives + /// (#3187). Where two border edges meet along a side, their handles are made collinear, so the + /// border stays smooth there; the four corners keep the handles their own edges were fitted with. + fn fit_border(&mut self, coons: &Coons, us: &[f64], vs: &[f64]) { + let (rows, cols) = (self.rows as usize, self.cols as usize); + if !self.is_valid() || us.len() != cols + 1 || vs.len() != rows + 1 { + return; + } + let edges = [(0, &coons.top), (rows, &coons.bottom)] + .map(|(r, side)| (r, side, true)) + .into_iter() + .chain([(0, &coons.left), (cols, &coons.right)].map(|(c, side)| (c, side, false))); + for (line, side, along_u) in edges { + let (n, steps) = if along_u { (cols, us) } else { (rows, vs) }; + for k in 0..n { + let (a, b, out, back) = if along_u { + (self.idx(line, k), self.idx(line, k + 1), H_RIGHT, H_LEFT) + } else { + (self.idx(k, line), self.idx(k + 1, line), H_DOWN, H_UP) + }; + if let Some((h1, h2)) = fit_edge(side, (steps[k], steps[k + 1]), (self.points[a].p, self.points[b].p)) { + self.points[a].handles[out] = h1; + self.points[b].handles[back] = h2; + } + } + for k in 1..n { + let (i, out, back) = if along_u { (self.idx(line, k), H_RIGHT, H_LEFT) } else { (self.idx(k, line), H_DOWN, H_UP) }; + let h = &mut self.points[i].handles; + let (fwd, bwd) = (h[out], h[back]); + let dir = (fwd.normalize() - bwd.normalize()).normalize(); + if fwd.hypot2() > 0.0 && bwd.hypot2() > 0.0 && dir.is_finite() { + h[out] = dir * fwd.hypot(); + h[back] = -dir * bwd.hypot(); + } + } + } } /// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to - /// the edges, by at most `highlight` %. + /// the edges, by at most `highlight` %. Each point lightens towards white in its own colour + /// model (paper white, no ink, for CMYK), so a CMYK or grey mesh keeps its inks (#3232). pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) { let h = (highlight / 100.0).clamp(0.0, 1.0) as f32; let (rows, cols) = (self.rows as usize, self.cols as usize); @@ -282,7 +415,8 @@ impl GradientMesh { }; if w > 0.0 { let i = self.idx(r, c); - self.points[i].color = lerp_color(&self.points[i].color, &Color::WHITE, w); + let color = self.points[i].color; + self.points[i].color = lerp_color(&color, &Color::WHITE.in_model(color.model()), w); } } } @@ -345,13 +479,20 @@ impl GradientMesh { (Color::rgb(rgb[0], rgb[1], rgb[2]), op) } - /// Tessellate into `n`×`n` quads per patch, each coloured at its centre and its corners. + /// The quads per patch side [`Self::quads`] cuts at when `n` is asked: 1 to 64, and coarser + /// where the patches at `n` would pass [`Self::MAX_QUADS`] (a quad per patch is the least). + fn subdivision(&self, n: usize) -> usize { + n.clamp(1, 64).min(((Self::MAX_QUADS / self.patches().max(1)) as f64).sqrt() as usize).max(1) + } + + /// Tessellate into `n`×`n` quads per patch ([`Self::subdivision`]), each coloured at its centre + /// and its corners. pub fn quads(&self, n: usize) -> Vec { if !self.is_valid() { return vec![]; } - let n = n.clamp(1, 64); - let mut out = Vec::with_capacity(self.rows as usize * self.cols as usize * n * n); + let n = self.subdivision(n); + let mut out = Vec::with_capacity(self.patches() * n * n); let mut grid = vec![Point::ZERO; (n + 1) * (n + 1)]; let mut colors = vec![(Color::default(), 0.0f32); (n + 1) * (n + 1)]; for r in 0..self.rows as usize { @@ -381,6 +522,105 @@ impl GradientMesh { out } + /// Flat-coloured pieces covering the mesh, for outputs that can't shade a mesh smoothly (SVG, + /// Expand): each patch cut into `n`×`n` quads as by [`Self::quads`], then neighbouring quads + /// joined into square blocks as large as keeps the colour across each block within about one + /// 8-bit step. A patch of one colour is one piece; a patch whose colour changes a lot keeps + /// all its quads. A piece's outline runs through its quads' outer corners, so it covers what + /// they covered, and it takes the colour at its centre. + pub fn pieces(&self, n: usize) -> Vec { + let n = self.subdivision(n); + let quads = self.quads(n); + let cols = (self.cols as usize).max(1); + let mut out = Vec::with_capacity(quads.len()); + for (k, patch) in quads.chunks_exact(n * n).enumerate() { + let (r, c) = (k / cols, k % cols); + let side = self.block_side(r, c, n, patch); + if side == 1 { + out.extend(patch.iter().map(|q| MeshPiece { pts: q.pts.to_vec(), color: q.color, opacity: q.opacity })); + continue; + } + // Tessellation point (i, j) of the patch (0..=n each), from a quad it is a corner of. + let at = |i: usize, j: usize| -> Option { + let (qi, qj) = (i.min(n - 1), j.min(n - 1)); + let q = patch.get(qj * n + qi)?; + q.pts + .get(match (i > qi, j > qj) { + (false, false) => 0, + (true, false) => 1, + (true, true) => 2, + (false, true) => 3, + }) + .copied() + }; + for j0 in (0..n).step_by(side) { + for i0 in (0..n).step_by(side) { + let (i1, j1) = (i0 + side, j0 + side); + // Around the block, in the quads' order: along its top, down its right side, + // back along its bottom and up its left side. + let ring = (i0..i1) + .map(|i| (i, j0)) + .chain((j0..j1).map(|j| (i1, j))) + .chain((i0 + 1..=i1).rev().map(|i| (i, j1))) + .chain((j0 + 1..=j1).rev().map(|j| (i0, j))); + let Some(pts) = ring.map(|(i, j)| at(i, j)).collect::>>() else { continue }; + let half = side as f64 / 2.0; + let (color, opacity) = self.color_at(r, c, (i0 as f64 + half) / n as f64, (j0 as f64 + half) / n as f64); + out.push(MeshPiece { pts, color, opacity }); + } + } + } + out + } + + /// The side, in quads, of the blocks [`Self::pieces`] joins patch (r, c) into, cut into + /// `n`×`n` `quads`: the largest divisor of `n` that keeps the colour changing by at most one + /// 8-bit step across a block. 1 (no joining) where the patch folds over itself, as the outline + /// of a block across the fold wouldn't fill it as its quads do. + fn block_side(&self, r: usize, c: usize, n: usize, quads: &[MeshQuad]) -> usize { + let corner = |dr: usize, dc: usize| self.points.get(self.idx(r + dr, c + dc)); + let (Some(p00), Some(p01), Some(p10), Some(p11)) = (corner(0, 0), corner(0, 1), corner(1, 0), corner(1, 1)) else { + return 1; + }; + // Corners all in CMYK mix in their inks ([`Self::color_at`]); the RGB they show is checked too. + let inks = [p00, p01, p10, p11].iter().all(|p| matches!(p.color, Color::Cmyk { .. })); + let channels = |p: &MeshPoint| -> Vec { + let mut v = p.color.to_rgb().to_vec(); + if inks && let Color::Cmyk { c, m, y, k } = p.color { + v.extend([c, m, y, k]); + } + v.push(p.opacity); + v + }; + let [a, b, cc, d] = [p00, p01, p10, p11].map(channels); + // A bilinear patch changes across a block of side h (0..1 of the patch) by at most + // h × (du + dv) in each channel, du and dv its largest change along each parameter. + let mut steps = 0.0f32; + for k in 0..a.len() { + let ch = |v: &[f32]| v.get(k).copied().unwrap_or_default(); + let du = (ch(&a) - ch(&b)).abs().max((ch(&cc) - ch(&d)).abs()); + let dv = (ch(&a) - ch(&cc)).abs().max((ch(&b) - ch(&d)).abs()); + steps = steps.max((du + dv) * 255.0); + } + if !steps.is_finite() { + return 1; + } + let side = (1..=n).rev().find(|&s| n.is_multiple_of(s) && (n / s) as f32 >= steps).unwrap_or(1); + if side > 1 { + // Every quad turning the same way: the patch doesn't fold, so a block's outline + // encloses just what its quads cover. + let turn = |q: &MeshQuad| { + let [a, b, c, d] = q.pts; + (b - a).cross(c - a) + (c - a).cross(d - a) + }; + let first = quads.first().map(turn).unwrap_or_default(); + if !quads.iter().all(|q| turn(q) * first > 0.0) { + return 1; + } + } + side + } + /// The mesh's outer boundary as a closed path. pub fn outline(&self) -> PathData { if !self.is_valid() { @@ -464,12 +704,21 @@ impl GradientMesh { /// Which patch and local (u, v) contains `p` (sampled search; `None` outside the mesh). pub fn locate(&self, p: Point) -> Option<(usize, usize, f64, f64)> { + self.locate_within(p, 0.0) + } + + /// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the + /// patch and local (u, v) of the nearest point of the mesh's edge. + pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> { if !self.is_valid() { return None; } let bp = self.outline().to_bezpath(); if bp.winding(p) == 0 { - return None; + if tol.is_nan() || tol <= 0.0 { + return None; + } + return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v)); } const N: usize = 16; let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0); @@ -506,6 +755,30 @@ impl GradientMesh { Some((r, c, u, v)) } + /// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its + /// boundary patch and local (u, v). + fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> { + use vectorcraft_geom::kurbo::ParamCurveNearest; + let (rows, cols) = (self.rows as usize, self.cols as usize); + let mut best: Option<(f64, usize, usize, f64, f64)> = None; + let mut take = |e: CubicBez, at: (usize, usize, Option, Option)| { + let n = e.nearest(p, 1e-9); + if best.is_none_or(|b| n.distance_sq < b.0) { + let (r, c, u, v) = at; + best = Some((n.distance_sq, r, c, u.unwrap_or(n.t), v.unwrap_or(n.t))); + } + }; + for c in 0..cols { + take(self.edge_u(0, c), (0, c, None, Some(0.0))); + take(self.edge_u(rows, c), (rows - 1, c, None, Some(1.0))); + } + for r in 0..rows { + take(self.edge_v(r, 0), (r, 0, Some(0.0), None)); + take(self.edge_v(r, cols), (r, cols - 1, Some(1.0), None)); + } + best + } + /// Index of the mesh point within `tol` of `p`. pub fn point_near(&self, p: Point, tol: f64) -> Option { self.points @@ -593,9 +866,10 @@ impl GradientMesh { self.cols += 1; } - /// Mesh tool click: add a row and a column through `p` (inside the mesh). Returns the new point index. - pub fn add_lines_at(&mut self, p: Point) -> Option { - let (r, c, u, v) = self.locate(p)?; + /// Mesh tool click: add a row and a column through `p` (inside the mesh, or outside within + /// `tol` of its edge, through the nearest point of the edge). Returns the new point index. + pub fn add_lines_at(&mut self, p: Point, tol: f64) -> Option { + let (r, c, u, v) = self.locate_within(p, tol)?; let mut rr = r; let mut cc = c; let row_new = v > 0.02 && v < 0.98; @@ -630,10 +904,11 @@ impl GradientMesh { let above = self.idx(r - 1, cc); let below = self.idx(r + 1, cc); let mid = self.idx(r, cc); - let (pa, pm, pb) = (self.points[above].p, self.points[mid].p, self.points[below].p); - let _ = pm; - self.points[above].handles[H_DOWN] = (pb - pa) / 3.0; - self.points[below].handles[H_UP] = (pa - pb) / 3.0; + let (pa, pb, m) = (self.points[above].p, self.points[below].p, &self.points[mid]); + let hm = (m.p, m.handles[H_UP], m.handles[H_DOWN]); + let (down, up) = merged_handles((pa, self.points[above].handles[H_DOWN]), hm, (pb, self.points[below].handles[H_UP])); + self.points[above].handles[H_DOWN] = down; + self.points[below].handles[H_UP] = up; } self.points.drain(r * w..(r + 1) * w); self.rows -= 1; @@ -644,9 +919,11 @@ impl GradientMesh { let rows = self.rows as usize; for rr in 0..=rows { let (l, rt) = (rr * w + c - 1, rr * w + c + 1); - let (pl, pr) = (self.points[l].p, self.points[rt].p); - self.points[l].handles[H_RIGHT] = (pr - pl) / 3.0; - self.points[rt].handles[H_LEFT] = (pl - pr) / 3.0; + let (pl, pr, m) = (self.points[l].p, self.points[rt].p, &self.points[rr * w + c]); + let hm = (m.p, m.handles[H_LEFT], m.handles[H_RIGHT]); + let (right, left) = merged_handles((pl, self.points[l].handles[H_RIGHT]), hm, (pr, self.points[rt].handles[H_LEFT])); + self.points[l].handles[H_RIGHT] = right; + self.points[rt].handles[H_LEFT] = left; } let mut k = 0; self.points.retain(|_| { diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 771b0b7fb6..a1268505fb 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -250,9 +250,13 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective); - b += boxed(&e.dimension) + boxed(&e.live_paint_gaps); + b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize); 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)); + if e.intertwine_tiers.capacity() > 0 { + b += ALLOC + e.intertwine_tiers.capacity() * size_of::() + e.intertwine_tiers.iter().map(path_bytes).sum::(); + } + b += e.symbol_overrides.capacity() * size_of::(); b += e.objects_on_path.as_deref().map_or(0, |o| { ALLOC + size_of::() + o.members.capacity() * size_of::() }); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 2d8ad8c9c0..239dce93c6 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -44,11 +44,28 @@ pub struct NodeExtras { /// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates, /// filled non-zero) where this object is drawn over the group's other members. pub intertwine: Option>, + /// Object › Intertwine: as a member of an Intertwine group, the areas (document coordinates, + /// filled non-zero) where this object is drawn over members that are themselves drawn over + /// others there. Item `k` is the area of tier `k + 2`; [`NodeExtras::intertwine`] is tier 1 + /// (see [`crate::intertwine`]). + pub intertwine_tiers: Vec, /// 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>, + /// A grayscale or 1-bit image's fill color (`paint.setFill` on the image): a solid paint that + /// colorizes it. Each pixel is drawn in this color, as opaque as the pixel is dark, so white + /// pixels are transparent. `None`: the image shows its own pixels. + pub colorize: Option>, + /// Pathfinder panel › Make Compound Shape: this group is a compound shape + /// ([`Node::is_compound_shape`], [`crate::compound_shape`]). + pub compound_shape: bool, + /// As a member of a compound shape, how this object combines with the members below it. + pub shape_mode: crate::ShapeMode, + /// As an instance of a dynamic symbol, its own appearance changes to objects of the symbol's + /// art (see [`crate::symbol_overrides`]); empty for none. + pub symbol_overrides: Vec, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -67,8 +84,13 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { perspective: None, dimension: None, intertwine: None, + intertwine_tiers: Vec::new(), live_paint_gaps: None, objects_on_path: None, + colorize: None, + compound_shape: false, + shape_mode: crate::ShapeMode::Add, + symbol_overrides: Vec::new(), }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index e02958a8dd..b5ae03e8b1 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -127,6 +127,7 @@ impl Node { NodeKind::Layer { .. } => "Layer", NodeKind::Group { clip: true, .. } => "Clip Group", NodeKind::Group { .. } if self.extras().objects_on_path.is_some() => "Objects on Path", + NodeKind::Group { .. } if self.extras().compound_shape => "Compound Shape", NodeKind::Group { .. } => "Group", NodeKind::Path { live: Some(l), .. } => l.label(), NodeKind::Path { guide: true, .. } => "Guide", @@ -197,7 +198,8 @@ impl Node { /// ([`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`]. + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box + /// takes in where its spine can put its keys and steps. pub fn reach_bounds(&self) -> Option { self.reach(None) } @@ -233,6 +235,11 @@ impl Node { 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))) }), + // Keys and steps placed on a spine, turned to it with Align to Path, can reach past the + // keys and the spine. + NodeKind::Blend { children, spec } => { + vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols)) + } _ => self.visual(symbols), } } @@ -495,8 +502,13 @@ impl Node { Arc::make_mut(&mut m.art).transform_scaled(a, sc); } // The area where an Intertwine member is drawn over the others moves with it. - if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) { - area.transform(a); + if let Some(e) = self.extras_if_any() { + if let Some(area) = e.intertwine.as_mut() { + area.transform(a); + } + for area in &mut e.intertwine_tiers { + area.transform(a); + } } } @@ -545,9 +557,16 @@ impl Node { /// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise /// type objects paint their runs (the first run speaks for all) in text space, fitted to the /// layout bounds; everything else paints its fill or stroke in the document, fitted to the - /// geometric bounds. Strokes fit the box grown by half their weight. + /// geometric bounds. Strokes fit the box grown by half their weight. A colorized image shows + /// its colorize paint as its fill. pub fn proxy_paint(&self, stroke: bool, item: Option) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> { let item = self.appearance.item_of_kind(item, !stroke); + if item.is_none() + && !stroke + && let Some(c) = self.extras().colorize.as_deref() + { + return Some((c, Affine::IDENTITY, self.geometric_bounds().unwrap_or(Rect::ZERO))); + } if item.is_none() && let NodeKind::Text(t) = &self.kind { @@ -675,9 +694,15 @@ impl Node { impl Node { /// Whether this object shows any transparency, itself or anything inside it: object, fill or - /// stroke opacity below 100%, a blend mode, an opacity mask, effects or transparent gradient - /// stops. Hidden objects show none. + /// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient + /// stops or a colorized image. Hidden objects show none. pub fn shows_transparency(&self) -> bool { + self.shows_transparency_with(&|_| true) + } + + /// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize` + /// accepts it, for files that write some colorized images in their colorize paint (EPS). + pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool { use vectorcraft_color::Paint; let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible); @@ -685,13 +710,14 @@ impl Node { && (self.opacity < 1.0 || self.blend != BlendMode::Normal || self.extras().mask.as_ref().is_some_and(|m| !m.disabled) + || (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self)) || effects(&self.appearance.effects) || self .appearance .items .iter() .any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects()))) - || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency()))) + || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize)))) } } diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 0565c9e079..df675580e2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -19,6 +19,8 @@ fn extras_are_written_flat_in_order() { e.slice = Some(Box::default()); e.perspective = Some(Box::new(crate::PerspectiveAttachment::new("left", 1.0))); e.live_paint_gaps = Some(Box::default()); + e.compound_shape = true; + e.shape_mode = crate::ShapeMode::Exclude; } /// The top-level keys of a JSON object, in the order written. struct Keys(Vec); @@ -61,8 +63,11 @@ fn extras_are_written_flat_in_order() { "bbox_angle", "perspective", "live_paint_gaps", + "compound_shape", + "shape_mode", ]; assert_eq!(keys, order); + assert_eq!(v["shape_mode"], "exclude"); assert_eq!(serde_json::from_value::(v).unwrap(), n); let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art()); let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap(); @@ -334,6 +339,35 @@ fn transform_group_recurses() { assert_eq!(child.appearance.stroke_width(), 2.0); } +/// A symbol instance in perspective keeps its picture moved by a transform, and loses its +/// projection when no invertible map of finite numbers draws the moved picture. +#[test] +fn a_projection_follows_the_transform_or_is_removed() { + use vectorcraft_geom::{Homography, Point}; + let instance = |h: Homography| { + let mut n = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::IDENTITY }); + n.extras_mut().perspective = + Some(Box::new(crate::PerspectiveAttachment { projection: Some(h.to_array()), ..crate::PerspectiveAttachment::new("left", 0.0) })); + n + }; + let projection = |n: &Node| n.extras().perspective.as_deref().and_then(|p| p.projection); + // A move by 10 scaled by 1e307: moved by a scale by 10, the product overflows unless scaled down. + let big = Homography([[1e307, 0.0, 1e308], [0.0, 1e307, 0.0], [0.0, 0.0, 1e307]]); + let mut n = instance(big); + n.transform(Affine::scale(10.0), false); + let p = Point::new(3.0, 7.0); + assert!(n.projection().unwrap().apply(p).unwrap().distance(Point::new(103.0, 7.0)) < 1e-9); + // A move by 1e200 moved by a scale by 1e150 sends every point to about (1e350, 0). + let far = Homography([[1.0, 0.0, 1e200], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); + let mut n = instance(far); + n.transform(Affine::scale(1e150), false); + assert_eq!(projection(&n), None); + // A transform that is not invertible leaves the projection as it is. + let mut n = instance(far); + n.transform(Affine::scale(0.0), false); + assert_eq!(projection(&n), Some(far.to_array())); +} + #[test] fn unplaced_gradients_pin_only_when_a_refit_would_differ() { use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint}; @@ -450,6 +484,23 @@ fn objects_are_read_within_the_node_budget() { assert!(with_node_budget(3, read).is_ok()); } +/// An Intertwine member's areas of tier 2 and up are written and read back, and each one counts +/// against [`with_node_budget`] as an object does, so a file of many empty areas is refused. +#[test] +fn intertwine_tiers_are_read_within_the_node_budget() { + let mut n = Node::group(NodeId(1), vec![]); + let area = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + n.extras_mut().intertwine_tiers = vec![PathData::default(), area]; + let json = serde_json::to_string(&n).unwrap(); + assert!(json.contains("\"intertwine_tiers\""), "{json}"); + let read = || serde_json::from_str::(&json); + assert_eq!(with_node_budget(3, read).unwrap(), n, "the object and its two areas fit a budget of three"); + let why = with_node_budget(2, read).unwrap_err().to_string(); + assert!(why.contains("more than 2 objects"), "{why}"); + let plain = serde_json::to_string(&Node::group(NodeId(1), vec![])).unwrap(); + assert!(!plain.contains("intertwine_tiers"), "an object without tiers writes none: {plain}"); +} + /// #3587: fields read before an object's `type` are buffered value by value within /// [`with_buffered_value_budget`], each counted once: a group read back from the buffer buffers /// its own fields again without counting them twice. VectorCraft writes `type` first, which diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 84d0b220eb..ed81b13915 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -5,6 +5,12 @@ use super::kind::NodeKind; use super::opacity::{Knockout, OpacityMask}; use super::{Appearance, BlendMode, Deserialize, Node, PathData, Serialize, one, yes}; +/// Field `name` of a [`Node`] written as `v`, or skipped. A function of its own, so the long field +/// list stays one straight run of calls. +fn write_field(st: &mut S, skip: bool, name: &'static str, v: &T) -> Result<(), S::Error> { + if skip { st.skip_field(name) } else { st.serialize_field(name, v) } +} + /// How a [`Node`] is written: the flat field list of the file format, in its order, borrowed from /// the node and its extras (nothing is copied). The node reads back through `NodeWire`. impl Serialize for Node { @@ -40,18 +46,19 @@ impl Serialize for Node { e.perspective.is_none(), e.dimension.is_none(), e.intertwine.is_none(), + e.intertwine_tiers.is_empty(), e.live_paint_gaps.is_none(), e.objects_on_path.is_none(), + e.colorize.is_none(), + is_default(&e.compound_shape), + is_default(&e.shape_mode), + e.symbol_overrides.is_empty(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); macro_rules! field { ($name:literal, $v:expr) => { - if skip.next().unwrap_or(false) { - st.skip_field($name)?; - } else { - st.serialize_field($name, $v)?; - } + write_field(&mut st, skip.next().unwrap_or(false), $name, $v)?; }; } field!("id", &self.id); @@ -80,8 +87,13 @@ impl Serialize for Node { field!("perspective", &e.perspective); field!("dimension", &e.dimension); field!("intertwine", &e.intertwine); + field!("intertwine_tiers", &e.intertwine_tiers); field!("live_paint_gaps", &e.live_paint_gaps); field!("objects_on_path", &e.objects_on_path); + field!("colorize", &e.colorize); + field!("compound_shape", &e.compound_shape); + field!("shape_mode", &e.shape_mode); + field!("symbol_overrides", &e.symbol_overrides); st.end() } } @@ -115,11 +127,39 @@ pub fn with_node_budget(max: usize, f: impl FnOnce() -> T) -> T { /// each counts once, and the id usually comes first, before the node's children are read. fn counted_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { let id = NodeId::deserialize(d)?; + count_one()?; + Ok(id) +} + +/// Count one object against [`with_node_budget`]. +fn count_one() -> Result<(), E> { if let Some((left, max)) = NODES_LEFT.get() { - let left = left.checked_sub(1).ok_or_else(|| serde::de::Error::custom(format!("the document has more than {max} objects")))?; + let left = left.checked_sub(1).ok_or_else(|| E::custom(format!("the document has more than {max} objects")))?; NODES_LEFT.set(Some((left, max))); } - Ok(id) + Ok(()) +} + +/// A list read from a file (a member's Intertwine areas of tier 2 and up, an instance's symbol +/// overrides), each item counting against [`with_node_budget`] as an object does: a compressed +/// file of repeated empty items stays small while they take memory once read. +fn counted_list<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result, D::Error> { + struct Items(std::marker::PhantomData); + impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Items { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::new(); + while let Some(item) = seq.next_element::()? { + count_one()?; + out.push(item); + } + Ok(out) + } + } + d.deserialize_seq(Items(std::marker::PhantomData)) } /// How a [`Node`] is read: the flat field list of the file format. Fields move into the node @@ -178,10 +218,20 @@ pub(super) struct NodeWire { dimension: Option>, #[serde(default)] intertwine: Option>, + #[serde(default, deserialize_with = "counted_list")] + intertwine_tiers: Vec, #[serde(default)] live_paint_gaps: Option>, #[serde(default)] objects_on_path: Option>, + #[serde(default)] + colorize: Option>, + #[serde(default)] + compound_shape: bool, + #[serde(default)] + shape_mode: crate::ShapeMode, + #[serde(default, deserialize_with = "counted_list")] + symbol_overrides: Vec, } impl From for Node { @@ -201,8 +251,13 @@ impl From for Node { perspective: w.perspective, dimension: w.dimension, intertwine: w.intertwine, + intertwine_tiers: w.intertwine_tiers, live_paint_gaps: w.live_paint_gaps, objects_on_path: w.objects_on_path, + colorize: w.colorize, + compound_shape: w.compound_shape, + shape_mode: w.shape_mode, + symbol_overrides: w.symbol_overrides, }; Node { id: w.id, diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index ca2ec7dd99..779e2eced3 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -337,7 +337,7 @@ mod tests { // 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))) }); + d.symbols.push(crate::Symbol { dynamic: false, 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)); diff --git a/crates/doc/src/orient.rs b/crates/doc/src/orient.rs index 43c67d86f3..114a152909 100644 --- a/crates/doc/src/orient.rs +++ b/crates/doc/src/orient.rs @@ -200,7 +200,7 @@ mod tests { fn oriented_bounds_hug_a_rotated_symbol_instances_art() { let mut d = Document::new(500.0, 500.0); let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 10.0)), Appearance::default_art()); - d.symbols.push(crate::Symbol { name: "Bar".into(), art: std::sync::Arc::new(bar) }); + d.symbols.push(crate::Symbol { dynamic: false, name: "Bar".into(), art: std::sync::Arc::new(bar) }); let (l, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::translate((100.0, 100.0)) })).unwrap(); let c = Point::new(120.0, 105.0); diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index 4de3823dba..6ec18bcfa2 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -58,12 +58,14 @@ impl Node { } } - /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). + /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An + /// invertible `a` that the projection cannot follow removes it, and the art is drawn flat. pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) { if let Some(p) = self.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) - && let Some(h) = p.homography().and_then(|h| h.conjugated(a)) + && let Some(h) = p.homography() + && a.determinant().abs() >= 1e-15 { - p.projection = Some(h.to_array()); + p.projection = h.conjugated(a).map(|h| h.to_array()); } } } diff --git a/crates/doc/src/pixels.rs b/crates/doc/src/pixels.rs index 306c8360e8..2264e66ce0 100644 --- a/crates/doc/src/pixels.rs +++ b/crates/doc/src/pixels.rs @@ -62,6 +62,61 @@ impl ImageBlob { } } +/// How a grayscale image's file stores its pixels ([`ImageBlob::gray_source`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GraySource { + /// One bit a pixel: black and white only. + pub one_bit: bool, + /// The file has an alpha channel. + pub alpha: bool, +} + +impl ImageBlob { + /// Whether the image's file stores grayscale or 1-bit pixels (the images a fill color + /// colorizes), and how; `None` for color images and data that isn't an image. Reads only its + /// header. + pub fn gray_source(&self) -> Option { + let gray = |one_bit: bool, alpha: bool| Some(GraySource { one_bit, alpha }); + if let Some((kind, _)) = crate::cmyk::tiff(&self.bytes) { + return match kind { + tiff::ColorType::Gray(bits) => gray(bits == 1, false), + tiff::ColorType::GrayA(bits) => gray(bits == 1, true), + _ => None, + }; + } + if crate::cmyk::jpeg_components(&self.bytes) == Some(1) { + return gray(false, false); + } + use image::{ExtendedColorType as E, ImageDecoder as _}; + let reader = image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?; + match reader.into_decoder().ok()?.original_color_type() { + E::L1 => gray(true, false), + E::La1 => gray(true, true), + E::L2 | E::L4 | E::L8 | E::L16 => gray(false, false), + E::La2 | E::La4 | E::La8 | E::La16 => gray(false, true), + _ => None, + } + } + + /// How much of a colorize paint each pixel shows, row by row from the top: how dark the pixel + /// is (255 less its Rec. 709 luma) scaled by its alpha, so white and transparent pixels are 0. + /// Returns the width, the height and one byte a pixel; `None` when the image can't be decoded + /// within [`MAX_RASTER_ALLOC`]. + pub fn coverage(&self) -> Option<(u32, u32, Vec)> { + let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?; + let (w, h) = img.dimensions(); + let cover = img + .pixels() + .map(|p| { + let [r, g, b, a] = p.0; + let luma = 0.2126 * r as f32 + 0.7152 * g as f32 + 0.0722 * b as f32; + ((255.0 - luma).clamp(0.0, 255.0) * a as f32 / 255.0).round() as u8 + }) + .collect(); + Some((w, h, cover)) + } +} + impl ImageBlob { /// The colour around pixel (`x`, `y`) (pixel space): the alpha-weighted average of the `size` × /// `size` pixels centred on it, clipped to the image, as straight RGBA. `None` outside the @@ -298,4 +353,66 @@ mod tests { assert!(b.map_rgb(|c| c).is_none(), "nothing changed"); assert!(ImageBlob::png(vec![1, 2, 3]).map_rgb(|c| c).is_none(), "undecodable"); } + + /// An uncompressed 1-bit TIFF, BlackIsZero, of `w` × `h` pixels: `rows` holds each row's bits, + /// padded to a byte, most significant bit first. + fn bilevel_tiff(w: u16, h: u16, rows: &[u8]) -> Vec { + // Tag, type (3 short, 4 long) and value of each entry, in tag order. + let data_at = 8 + 2 + 9 * 12 + 4; + let entries: [(u16, u16, u32); 9] = [ + (256, 3, w.into()), + (257, 3, h.into()), + (258, 3, 1), + (259, 3, 1), + (262, 3, 1), + (273, 4, data_at), + (277, 3, 1), + (278, 3, h.into()), + (279, 4, rows.len() as u32), + ]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (tag, kind, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(rows); + out + } + + fn png_of(img: image::DynamicImage) -> ImageBlob { + let mut png = Vec::new(); + img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + ImageBlob::png(png) + } + + #[test] + fn grayscale_and_1_bit_files_are_told_from_color_ones() { + let gray = |one_bit, alpha| Some(GraySource { one_bit, alpha }); + let l8 = png_of(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())); + assert_eq!(l8.gray_source(), gray(false, false)); + let la8 = png_of(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(1, 1, vec![0, 128]).unwrap())); + assert_eq!(la8.gray_source(), gray(false, true)); + let mut jpeg = Vec::new(); + jpeg_encoder::Encoder::new(&mut jpeg, 90).encode(&[0, 255, 0, 255], 2, 2, jpeg_encoder::ColorType::Luma).unwrap(); + assert_eq!(ImageBlob::new("image/jpeg", jpeg).gray_source(), gray(false, false)); + // Black, white; white, black. + let tif = ImageBlob::new("image/tiff", bilevel_tiff(2, 2, &[0b0100_0000, 0b1000_0000])); + assert_eq!(tif.gray_source(), gray(true, false)); + assert_eq!(tif.coverage(), Some((2, 2, vec![255, 0, 0, 255])), "black covers, white doesn't"); + // Color images and data that isn't an image. + assert_eq!(blob(&[[0, 0, 0, 255], [9, 9, 9, 255]], 2, 1).gray_source(), None); + assert_eq!(ImageBlob::png(vec![1, 2, 3]).gray_source(), None); + } + + #[test] + fn coverage_is_darkness_times_alpha() { + let la8 = png_of(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(4, 1, vec![0, 255, 255, 255, 51, 255, 0, 128]).unwrap())); + assert_eq!(la8.coverage(), Some((4, 1, vec![255, 0, 204, 128]))); + assert_eq!(ImageBlob::png(vec![1, 2, 3]).coverage(), None); + } } diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 9b00da57eb..310d7b784f 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -667,7 +667,7 @@ mod tests { pixels: None, })), ); - d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Star".into(), art: Arc::new(art) }); d.images.insert("pic".into(), ImageBlob::new("image/png", vec![1, 2, 3])); let mut children = vec![Arc::new(Node::new(NodeId(51), NodeKind::SymbolInstance { symbol: "Star".into(), xf: Affine::IDENTITY }))]; if bytes.starts_with(b"nest") { @@ -702,7 +702,11 @@ mod tests { fn the_art_and_its_resources_join_only_a_prepared_copy_under_their_own_names() { set_loader(stub_loader); let mut d = Document::new(200.0, 200.0); - d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })) }); + d.symbols.push(Symbol { + dynamic: false, + name: "Star".into(), + art: Arc::new(Node::new(NodeId(60), NodeKind::Group { children: vec![], clip: false })), + }); d.images.insert("doc1-1".into(), ImageBlob::new("application/json", b"nest".to_vec())); let p = placed("doc1-1"); let layer = d.layers[0].id; diff --git a/crates/doc/src/recolor.rs b/crates/doc/src/recolor.rs index a5a8787104..0efa82296a 100644 --- a/crates/doc/src/recolor.rs +++ b/crates/doc/src/recolor.rs @@ -18,8 +18,8 @@ pub trait ColorVisitor { fn image(&mut self, key: &str) -> Option; } -/// What a recolouring pass reaches: fills (with gradient-mesh points), strokes and the pixels of -/// embedded images. +/// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh +/// points), strokes and the pixels of embedded images without a colorize paint. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Reach { pub fill: bool, @@ -33,11 +33,18 @@ impl Reach { } /// Recolour `n` and everything inside it through `v`: the paints of its fills and strokes and of -/// its text runs, its gradient-mesh points and an embedded image's pixels (linked images stay -/// as they are). Members that change are replaced by copies; the others stay shared. Returns the -/// number of paints, meshes and images that changed. +/// its text runs, its gradient-mesh points and an embedded image's pixels (linked and colorized +/// images keep their pixels). Members that change are replaced by copies; the others stay shared. +/// Returns the number of paints, meshes and images that changed. pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usize { let mut changed = 0; + let colorized = matches!(&n.kind, NodeKind::Image(_)) && n.extras().colorize.is_some(); + if colorized + && reach.fill + && let Some(paint) = n.extras_mut().colorize.as_deref_mut() + { + changed += v.paint(paint) as usize; + } for it in &mut n.appearance.items { match it { AppearanceItem::Fill(l) if reach.fill => changed += v.paint(&mut l.paint) as usize, @@ -67,7 +74,7 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi } // An image holding its own pixels is a glyph's (emoji in outlined type): it keeps its // colours, as the glyph does in type. - NodeKind::Image(im) if reach.images && im.link.is_none() && im.pixels.is_none() => { + NodeKind::Image(im) if reach.images && !colorized && im.link.is_none() && im.pixels.is_none() => { if let Some(k) = v.image(&im.key) { im.key = k; changed += 1; diff --git a/crates/doc/src/records.rs b/crates/doc/src/records.rs index b13a1e955a..a6988f5020 100644 --- a/crates/doc/src/records.rs +++ b/crates/doc/src/records.rs @@ -1,4 +1,4 @@ -use super::{Arc, Deserialize, Node, NodeId, Point, Serialize}; +use super::{Affine, Arc, Deserialize, Node, NodeId, Point, Serialize}; /// New art on a locked artboard ([`Document::new_art`]). Setting it changes the document in /// place, so a selection change that sets it doesn't replace the document. @@ -44,6 +44,29 @@ pub struct MaskEdit { pub layer: NodeId, } +/// Symbol editing mode: the art of symbol `symbol` lives on the temporary `layer` while editing, +/// placed by `xf` (from the symbol's coordinates to the document's), and goes back into the symbol +/// after each edit, so every instance follows it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SymbolEdit { + pub symbol: String, + pub layer: NodeId, + /// The instance editing was entered from (a double-click on it), selected again on leaving after an edit; + /// `None` when it was entered from the Symbols panel. + pub instance: Option, + pub xf: Affine, + /// The symbol's art is a group whose members are on the layer: the group takes them back. + pub group: bool, + /// An edit changed the art since editing was entered. + pub changed: bool, + /// The isolated object from before editing was entered, isolated again on leaving. + #[serde(default)] + pub back_isolation: Option, + /// The current layer from before editing was entered, current again on leaving. + #[serde(default)] + pub back_layer: Option, +} + /// A saved view (View → New View…): zoom, centre and rotation, listed at the bottom of the View menu. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SavedView { @@ -108,6 +131,10 @@ impl SavedSelection { pub struct Symbol { pub name: String, pub art: Arc, + /// Symbol Options › Symbol Type › Dynamic Symbol: each instance may change the appearance of + /// objects in the art and stay linked (see [`crate::symbol_overrides`]). Static by default. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub dynamic: bool, } /// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects. diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 875fcf3a0c..c269181536 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -107,14 +107,17 @@ impl Quotes { /// Single-quote pairs offered by Document Setup. pub const SINGLE_CHOICES: &[[char; 2]] = &[['‘', '’'], ['‚', '‘'], ['‚', '’'], ['’', '’'], ['‹', '›'], ['›', '‹'], ['『', '』'], ['\'', '\'']]; - /// Is `c` one of these opening quotes? + /// Is `c` one of these opening quotes? A typographic glyph that is also a closing quote does not + /// count; a straight quote has no direction, so it still opens. fn is_open(&self, c: char) -> bool { - c == self.double[0] || c == self.single[0] + (c == self.double[0] || c == self.single[0]) && (c.is_ascii() || (c != self.double[1] && c != self.single[1])) } /// A quote opens after nothing, whitespace, an opening bracket, a dash or another opening quote. - fn opens(&self, prev: Option) -> bool { - prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || self.is_open(p)) + /// `quote_opened` says whether `prev` is a quote this conversion just produced, and if so whether + /// it opened; that settles glyphs which serve as both opening and closing quote. + fn opens(&self, prev: Option, quote_opened: Option) -> bool { + prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || quote_opened.unwrap_or_else(|| self.is_open(p))) } /// `text` with straight quotes (`"` and `'`) replaced by these quotes: opening or closing by @@ -122,11 +125,16 @@ impl Quotes { /// and is updated to its last character, so text can be converted in pieces. pub fn apply(&self, text: &str, prev: &mut Option) -> String { let mut out = String::with_capacity(text.len()); + let mut quote_opened = None; for c in text.chars() { - let r = match c { - '"' => self.double[usize::from(!self.opens(*prev))], - '\'' => self.single[usize::from(!self.opens(*prev))], - c => c, + quote_opened = match c { + '"' | '\'' => Some(self.opens(*prev, quote_opened)), + _ => None, + }; + let r = match (c, quote_opened) { + ('"', Some(open)) => self.double[usize::from(!open)], + ('\'', Some(open)) => self.single[usize::from(!open)], + (c, _) => c, }; out.push(r); *prev = Some(r); @@ -135,34 +143,74 @@ impl Quotes { } } -/// Document languages and the quote characters each uses (choosing a language in Document Setup -/// also picks its quotes). -pub const LANGUAGES: &[(&str, Quotes)] = &[ - ("English: USA", Quotes::ENGLISH), - ("English: UK", Quotes { double: ['“', '”'], single: ['‘', '’'] }), - ("German", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), - ("German: Swiss", Quotes { double: ['«', '»'], single: ['‹', '›'] }), - ("French", Quotes { double: ['«', '»'], single: ['‹', '›'] }), - ("Italian", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Spanish", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Catalan", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Portuguese", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Dutch", Quotes { double: ['“', '”'], single: ['‘', '’'] }), - ("Danish", Quotes { double: ['»', '«'], single: ['›', '‹'] }), - ("Swedish", Quotes { double: ['”', '”'], single: ['’', '’'] }), - ("Finnish", Quotes { double: ['”', '”'], single: ['’', '’'] }), - ("Norwegian", Quotes { double: ['«', '»'], single: ['‘', '’'] }), - ("Polish", Quotes { double: ['„', '”'], single: ['‚', '’'] }), - ("Czech", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), - ("Russian", Quotes { double: ['«', '»'], single: ['„', '“'] }), - ("Turkish", Quotes { double: ['“', '”'], single: ['‘', '’'] }), - ("Japanese", Quotes { double: ['「', '」'], single: ['『', '』'] }), - ("Chinese", Quotes { double: ['“', '”'], single: ['‘', '’'] }), +/// Document and character languages: the name, the BCP 47 tag text is shaped in (so that fonts use +/// their language's forms, OpenType `locl`) and the quote characters each uses (choosing a +/// language in Document Setup also picks its quotes). The first is the default. +pub const LANGUAGES: &[(&str, &str, Quotes)] = &[ + ("English: USA", "en-US", Quotes::ENGLISH), + ("English: UK", "en-GB", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("German", "de", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), + ("German: Swiss", "de-CH", Quotes { double: ['«', '»'], single: ['‹', '›'] }), + ("French", "fr", Quotes { double: ['«', '»'], single: ['‹', '›'] }), + ("Italian", "it", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Spanish", "es", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Catalan", "ca", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Portuguese", "pt", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Dutch", "nl", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("Danish", "da", Quotes { double: ['»', '«'], single: ['›', '‹'] }), + ("Swedish", "sv", Quotes { double: ['”', '”'], single: ['’', '’'] }), + ("Finnish", "fi", Quotes { double: ['”', '”'], single: ['’', '’'] }), + ("Norwegian", "nb", Quotes { double: ['«', '»'], single: ['‘', '’'] }), + ("Polish", "pl", Quotes { double: ['„', '”'], single: ['‚', '’'] }), + ("Czech", "cs", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), + ("Russian", "ru", Quotes { double: ['«', '»'], single: ['„', '“'] }), + // „…” outside, ’…’ inside: Pravopis srpskoga jezika (Matica srpska, 2010, ISBN + // 978-86-7946-079-0, т. 168, pp. 133–135) and CLDR + // (https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml, `delimiters`). + ("Serbian: Cyrillic", "sr-Cyrl", Quotes { double: ['„', '”'], single: ['’', '’'] }), + ("Serbian: Latin", "sr-Latn", Quotes { double: ['„', '”'], single: ['’', '’'] }), + // „…“ outside, ‚…‘ inside: CLDR (https://github.com/unicode-org/cldr/blob/main/common/main/hr.xml, + // `delimiters`). + ("Croatian", "hr", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), + ("Turkish", "tr", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("Japanese", "ja", Quotes { double: ['「', '」'], single: ['『', '』'] }), + ("Chinese", "zh", Quotes { double: ['“', '”'], single: ['‘', '’'] }), + ("Hindi", "hi", Quotes::ENGLISH), + ("Marathi", "mr", Quotes::ENGLISH), + ("Gujarati", "gu", Quotes::ENGLISH), + ("Bengali", "bn", Quotes::ENGLISH), + ("Punjabi", "pa", Quotes::ENGLISH), + ("Tamil", "ta", Quotes::ENGLISH), + ("Telugu", "te", Quotes::ENGLISH), + ("Kannada", "kn", Quotes::ENGLISH), + ("Malayalam", "ml", Quotes::ENGLISH), + ("Odia", "or", Quotes::ENGLISH), + ("Urdu", "ur", Quotes::ENGLISH), ]; /// The quotes of a [`LANGUAGES`] entry (case-insensitive). pub fn language_quotes(language: &str) -> Option { - LANGUAGES.iter().find(|(l, _)| l.eq_ignore_ascii_case(language)).map(|(_, q)| *q) + LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) +} + +/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's +/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the +/// first entry); `Err` for a language not in the list. +pub fn char_language(language: &str) -> Result, String> { + let i = LANGUAGES + .iter() + .position(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)) + .ok_or_else(|| format!("unknown language `{language}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::>().join(", ")))?; + Ok(LANGUAGES.get(i).filter(|_| i > 0).map(|(_, t, _)| *t)) +} + +/// The name of the language a character's stored `language` tag stands for: the default's for +/// none, `None` for a tag not in [`LANGUAGES`] (from a file). +pub fn char_language_name(language: Option<&str>) -> Option<&'static str> { + match language { + None => LANGUAGES.first().map(|(n, _, _)| *n), + Some(tag) => LANGUAGES.iter().find(|(_, t, _)| t.eq_ignore_ascii_case(tag)).map(|(n, _, _)| *n), + } } /// The transparency flattener preset Document Setup uses unless another is chosen. @@ -300,9 +348,19 @@ impl DocSetup { pub fn keep_in_range(&mut self) { self.bleed = bleed_in_range(self.bleed); for m in [&mut self.superscript, &mut self.subscript] { + // `clamp` passes NaN through, so a non-finite value falls back to the default first. + if !m.size.is_finite() { + m.size = ScriptMetrics::DEFAULT.size; + } + if !m.position.is_finite() { + m.position = ScriptMetrics::DEFAULT.position; + } m.size = m.size.clamp(1.0, MAX_SCRIPT); m.position = m.position.clamp(-MAX_SCRIPT, MAX_SCRIPT); } + if !self.small_caps_size.is_finite() { + self.small_caps_size = DocSetup::default().small_caps_size; + } self.small_caps_size = self.small_caps_size.clamp(1.0, MAX_SMALL_CAPS); } } @@ -311,6 +369,31 @@ impl DocSetup { mod tests { use super::*; + /// Characters store a language of the list by its tag, the default as none. + #[test] + fn char_languages_are_stored_by_tag() { + assert_eq!(char_language("Turkish"), Ok(Some("tr"))); + assert_eq!(char_language("MR"), Ok(Some("mr"))); + assert_eq!(char_language("english: usa"), Ok(None)); + assert_eq!(char_language("en-US"), Ok(None)); + assert!(char_language("Klingon").is_err() && char_language("").is_err()); + assert_eq!( + (char_language_name(None), char_language_name(Some("gu")), char_language_name(Some("x-unknown"))), + (Some("English: USA"), Some("Gujarati"), None) + ); + // Serbian in either script, and Croatian. + assert_eq!(char_language("Serbian: Cyrillic"), Ok(Some("sr-Cyrl"))); + assert_eq!(char_language("sr-latn"), Ok(Some("sr-Latn"))); + assert_eq!(char_language("Croatian"), Ok(Some("hr"))); + assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic")); + // Every entry has a tag of its own, and a name of its own. + for (i, (n, t, _)) in LANGUAGES.iter().enumerate() { + assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}"); + } + } + + /// Straight quotes become the language's: opening or closing by what comes before, inner + /// quotes as single ones, and the context carried across pieces converted apart. #[test] fn quotes_open_and_close_by_context() { let mut prev = None; @@ -319,6 +402,13 @@ mod tests { let mut prev = Some('('); assert_eq!(german.apply("\"a\"", &mut prev), "„a“"); assert_eq!(prev, Some('“')); + // Serbian closes high (”), with ’ on both sides of an inner quote; Croatian as German. + for name in ["Serbian: Cyrillic", "Serbian: Latin"] { + let mut prev = None; + assert_eq!(language_quotes(name).unwrap().apply("\"a 'b' c\"", &mut prev), "„a ’b’ c”", "{name}"); + } + let mut prev = None; + assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“"); // Converting in pieces keeps the context. let mut prev = None; let a = Quotes::ENGLISH.apply("\"", &mut prev); @@ -326,6 +416,18 @@ mod tests { assert_eq!((a.as_str(), b.as_str()), ("“", "“")); } + #[test] + fn closing_quote_equal_to_other_kinds_opening_quote_still_closes() { + let q = Quotes { double: ['”', '”'], single: ['‘', '’'] }; + let mut prev = None; + assert_eq!(q.apply("'\"a\"'", &mut prev), "‘”a”’"); + let q = Quotes { double: ['"', '"'], single: ['‘', '’'] }; + let mut prev = None; + assert_eq!(q.apply("'\"a\"'", &mut prev), "‘\"a\"’"); + let mut prev = None; + assert_eq!(q.apply("\"'a'\"", &mut prev), "\"‘a’\""); + } + #[test] fn bleed_grows_the_artboard() { let s = DocSetup { bleed: [9.0, 9.0, 4.0, 2.0], ..Default::default() }; @@ -333,6 +435,20 @@ mod tests { assert!(s.has_bleed() && !DocSetup::default().has_bleed()); } + #[test] + fn keep_in_range_replaces_non_finite_type_values() { + let mut s = DocSetup::default(); + s.superscript.size = f64::NAN; + s.superscript.position = f64::INFINITY; + s.subscript.size = f64::NEG_INFINITY; + s.subscript.position = f64::NAN; + s.small_caps_size = f64::NAN; + s.keep_in_range(); + for v in [s.superscript.size, s.superscript.position, s.subscript.size, s.subscript.position, s.small_caps_size] { + assert!(v.is_finite(), "{v}"); + } + } + #[test] fn presets_and_defaults() { let d = DocSetup::default(); diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 692fa868c7..95978bd8d2 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -229,13 +229,14 @@ fn item_paint_mut(it: &mut AppearanceItem) -> &mut Paint { } } -/// The paints a node holds itself (not its children): appearance items, then text runs. +/// The paints a node holds itself (not its children): appearance items, then text runs, then an +/// image's colorize paint. pub fn node_paints(n: &Node) -> impl Iterator { let runs = match &n.kind { NodeKind::Text(t) => t.runs.as_slice(), _ => &[], }; - n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])) + n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])).chain(n.extras().colorize.as_deref()) } /// Mutable [`node_paints`], in the same order. @@ -244,7 +245,8 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator { NodeKind::Text(t) => t.runs.as_mut_slice(), _ => &mut [], }; - n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])) + let colorize = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()); + n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize) } /// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then diff --git a/crates/doc/src/symbol_overrides.rs b/crates/doc/src/symbol_overrides.rs new file mode 100644 index 0000000000..b4e3a726f5 --- /dev/null +++ b/crates/doc/src/symbol_overrides.rs @@ -0,0 +1,190 @@ +//! Dynamic symbols (Symbol Options › Symbol Type › Dynamic Symbol): an instance of a dynamic +//! symbol keeps appearance changes of its own to objects in the symbol's art, while the art stays +//! the symbol's. Editing the symbol reshapes every instance and each keeps its changes; Reset drops +//! them. The changes are stored on the instance ([`crate::node::NodeExtras::symbol_overrides`]) and +//! applied wherever an instance is drawn or exported ([`dynamic_art`]). + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use vectorcraft_color::{BlendMode, Paint}; + +use crate::{Node, NodeKind}; + +/// Deepest object an override may name: groups nested this deep in the symbol's art. +pub const MAX_PATH_DEPTH: usize = 64; + +/// One instance's appearance changes to one object of its dynamic symbol's art. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct SymbolOverride { + /// The object: child indices (paint order) from the art's root down through its groups; empty + /// for the root itself. + #[serde(deserialize_with = "short_path")] + pub path: Vec, + /// The object's (top) fill paint; type takes it as its characters' fill. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill: Option, + /// The object's (top) stroke paint; type takes it as its characters' stroke. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stroke: Option, + /// The object's opacity, 0..1. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opacity: Option, + /// The object's blending mode. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub blend: Option, +} + +impl SymbolOverride { + /// Does this override change nothing? + pub fn is_empty(&self) -> bool { + self.fill.is_none() && self.stroke.is_none() && self.opacity.is_none() && self.blend.is_none() + } + + /// Put this override's changes on object `n`. + fn apply(&self, n: &mut Node) { + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + if let Some(p) = &self.fill { + r.style.fill = p.clone(); + } + if let Some(p) = &self.stroke { + r.style.stroke = p.clone(); + } + } + } else { + if let Some(p) = &self.fill { + n.appearance.set_fill(p.clone()); + } + if let Some(p) = &self.stroke { + n.appearance.set_stroke(p.clone()); + } + } + if let Some(o) = self.opacity.filter(|o| o.is_finite()) { + n.opacity = o.clamp(0.0, 1.0); + } + if let Some(b) = self.blend { + n.blend = b; + } + } +} + +/// An override's path read from a file: at most [`MAX_PATH_DEPTH`] indices, so a compressed file +/// of one endless path stays small once read. +fn short_path<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + struct Path; + impl<'de> serde::de::Visitor<'de> for Path { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list of child indices") + } + fn visit_seq>(self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::new(); + while let Some(i) = seq.next_element::()? { + if out.len() == MAX_PATH_DEPTH { + return Err(serde::de::Error::custom(format!("a symbol override path is deeper than {MAX_PATH_DEPTH}"))); + } + out.push(i); + } + Ok(out) + } + } + d.deserialize_seq(Path) +} + +/// The children a path steps through: a group's (clip groups included) or a layer's. +fn groups_children(n: &Node) -> Option<&Vec>> { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }).then(|| n.children()).flatten() +} + +/// The object `path` names in symbol art `art`, if there is one. +pub fn part<'a>(art: &'a Node, path: &[u32]) -> Option<&'a Node> { + if path.len() > MAX_PATH_DEPTH { + return None; + } + path.iter().try_fold(art, |n, &i| groups_children(n)?.get(i as usize).map(|c| &**c)) +} + +/// [`part`], to change (the nodes on the way are copied when shared). +fn part_mut<'a>(art: &'a mut Node, path: &[u32]) -> Option<&'a mut Node> { + let Some((&i, rest)) = path.split_first() else { return Some(art) }; + if !matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let c = art.children_mut()?.get_mut(i as usize)?; + part_mut(Arc::make_mut(c), rest) +} + +/// Put `overrides` on symbol art `art`; an override naming no object of it is left out. +pub fn apply(art: &mut Node, overrides: &[SymbolOverride]) { + for o in overrides.iter().filter(|o| o.path.len() <= MAX_PATH_DEPTH) { + if let Some(n) = part_mut(art, &o.path) { + o.apply(n); + } + } +} + +/// Symbol art `art` as instance `inst` shows it: a copy with the instance's overrides applied. +pub fn dynamic_art(art: &Node, inst: &Node) -> Node { + let mut a = art.clone(); + apply(&mut a, &inst.extras().symbol_overrides); + a +} + +/// Keep the overrides that name an object of `art` (a symbol's new art), dropping the rest. +pub fn retain_parts(overrides: &mut Vec, art: &Node) { + overrides.retain(|o| part(art, &o.path).is_some()); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Appearance, NodeId}; + use vectorcraft_color::Color; + use vectorcraft_geom::{Rect, shapes}; + + fn square(id: u64) -> Arc { + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())) + } + + fn art() -> Node { + let inner = Node::group(NodeId(3), vec![square(4), square(5)]); + Node::group(NodeId(1), vec![square(2), Arc::new(inner)]) + } + + #[test] + fn paths_name_objects_through_groups_only() { + let a = art(); + assert_eq!(part(&a, &[]).map(|n| n.id), Some(NodeId(1))); + assert_eq!(part(&a, &[1, 0]).map(|n| n.id), Some(NodeId(4))); + assert!(part(&a, &[2]).is_none()); + assert!(part(&a, &[0, 0]).is_none(), "a path has no children"); + assert!(part(&a, &[0; MAX_PATH_DEPTH + 1]).is_none()); + } + + #[test] + fn overrides_paint_their_object_and_skip_missing_ones() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let o = vec![ + SymbolOverride { path: vec![1, 1], fill: Some(red.clone()), opacity: Some(0.5), ..Default::default() }, + SymbolOverride { path: vec![9], fill: Some(red.clone()), ..Default::default() }, + ]; + let mut a = art(); + apply(&mut a, &o); + let n = part(&a, &[1, 1]).unwrap(); + assert_eq!(n.appearance.fill_paint(), red); + assert_eq!(n.opacity, 0.5); + assert_eq!(part(&a, &[1, 0]).unwrap().appearance.fill_paint(), Paint::solid(Color::WHITE), "its sibling keeps the symbol's look"); + let mut kept = o; + retain_parts(&mut kept, &a); + assert_eq!(kept.len(), 1); + } + + #[test] + fn a_path_deeper_than_the_cap_does_not_read() { + let deep = format!("{{\"path\":{:?}}}", vec![0; MAX_PATH_DEPTH + 1]); + assert!(serde_json::from_str::(&deep).is_err()); + let ok: SymbolOverride = serde_json::from_str("{\"path\":[1,0],\"opacity\":0.25}").unwrap(); + assert_eq!(ok, SymbolOverride { path: vec![1, 0], opacity: Some(0.25), ..Default::default() }); + } +} diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 8f095566b4..bb3cbf11f4 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -410,7 +410,7 @@ mod tests { /// Symbol `name` holding `art` in a group. fn symbol(d: &mut Document, name: &str, art: Vec) { let group = Node::group(d.alloc_id(), art.into_iter().map(Arc::new).collect()); - d.symbols.push(Symbol { name: name.into(), art: Arc::new(group) }); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) }); } #[test] diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a13fb21680..37e2d39bca 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -55,6 +55,29 @@ fn doc_with_rects() -> (Document, NodeId, NodeId) { (d, a, b) } +/// Output draws the background colors of the artboards asked for, and only theirs, as rectangles +/// of those artboards on a layer below the art; without a color there is nothing to draw. +#[test] +fn artboard_fills_go_below_the_art() { + let (mut d, a, _) = doc_with_rects(); + assert!(d.with_artboard_fills([0]).is_none(), "no color, no fill"); + let second = Rect::new(700.0, 0.0, 800.0, 100.0); + d.artboards.push(Artboard { id: 2, rect: second, ..d.artboards[0].clone() }); + let blue = vectorcraft_color::Color::cmyk(1.0, 0.5, 0.0, 0.0); + d.artboards[1].color = Some(blue); + assert!(d.with_artboard_fills([0]).is_none(), "only the artboards asked for"); + let out = d.with_artboard_fills([0, 1]).unwrap(); + assert_eq!(out.layers.len(), d.layers.len() + 1); + assert_eq!(out.layers[1..], d.layers[..], "the art stays as it was, above the fills"); + let fills = out.layers[0].children().unwrap(); + assert_eq!(out.layers[0].display_name(), "Artboard Fill"); + assert_eq!(fills.len(), 1); + assert_eq!(fills[0].geometric_bounds(), Some(second)); + assert_eq!(fills[0].appearance.fill_paint(), vectorcraft_color::Paint::solid(blue), "in the color's own model"); + assert!(out.node(a).is_some() && out.node(fills[0].id).is_some() && fills[0].id != a); + assert_eq!(d.artboards, out.artboards); +} + #[test] fn new_document_has_layer_and_artboard() { let d = Document::new(612.0, 792.0); @@ -202,7 +225,7 @@ fn art_on_a_locked_artboard_cannot_be_selected_or_edited() { fn art_on_artboard_measures_a_symbol_instance_by_its_art() { let mut d = Document::new(612.0, 792.0); let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) }); let (layer, id) = (d.layers[0].id, d.alloc_id()); d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((2.0, 2.0)) })).unwrap(); // The art, (2, 2) to (12, 12), lies inside; the 20 × 20 square, (-8, -8) to (12, 12), doesn't. @@ -388,6 +411,18 @@ fn char_position_round_trips() { assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9); } +#[test] +fn optical_kerning_round_trips_and_old_style_defaults_to_auto() { + let st = CharStyle { optical_kerning: true, kerning: Some(120.0), ..CharStyle::default() }; + let value = serde_json::to_value(&st).unwrap(); + assert_eq!(value["opticalKerning"], true); + assert_eq!(serde_json::from_value::(value.clone()).unwrap(), st); + let mut old = value; + old.as_object_mut().unwrap().remove("opticalKerning"); + assert!(!serde_json::from_value::(old).unwrap().optical_kerning); + assert!(serde_json::to_value(CharStyle::default()).unwrap().get("opticalKerning").is_none()); +} + #[test] fn units() { assert_eq!(Unit::Inches.parse("1"), Some(72.0)); diff --git a/crates/doc/src/tests/units.rs b/crates/doc/src/tests/units.rs index 909a0adf3b..88075a5dc0 100644 --- a/crates/doc/src/tests/units.rs +++ b/crates/doc/src/tests/units.rs @@ -144,3 +144,10 @@ fn mixed_mul_div() { assert_eq!(Unit::Points.parse("10*2/5"), Some(4.0)); assert_eq!(Unit::Points.parse("10*2/5 px"), Some(Unit::Pixels.to_pt(4.0))); } + +#[test] +fn readout_has_no_negative_zero() { + assert_eq!(Unit::Points.readout(-0.001), "0.00 pt"); + assert_eq!(Unit::Points.readout(-0.0), "0.00 pt"); + assert_eq!(Unit::Points.readout(-12.5), "-12.50 pt"); +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index a3ab2ccc56..675245b56b 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -13,9 +13,9 @@ mod para_style; mod runs; mod tabs_lists; -pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextWrap, VerticalAlign, WrapShape}; +pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; -pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, ScriptMetrics}; +pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, ScriptMetrics}; pub use para_style::{ Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, SingleWordJustify, diff --git a/crates/doc/src/text/area.rs b/crates/doc/src/text/area.rs index b30afd4128..f53a488571 100644 --- a/crates/doc/src/text/area.rs +++ b/crates/doc/src/text/area.rs @@ -29,6 +29,19 @@ impl VerticalAlign { } } +/// Area Type Options › Text Flow: the order text fills the cells of area type with several rows +/// and columns. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TextFlow { + /// Down each column's rows, then on to the next column (the default, and what a document + /// from before the option reads as). + #[default] + Columns, + /// Across each row's columns, then on to the next row. + Rows, +} + /// Text Wrap Options of a wrap object (Object → Text Wrap). #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -135,6 +148,9 @@ pub struct AreaOptions { pub first_baseline_min: f64, /// Vertical alignment of the lines in each row/column. pub vertical_align: VerticalAlign, + /// Text Flow: by columns (the default, left out when saved) or by rows. + #[serde(skip_serializing_if = "crate::skip::is_default")] + pub flow: TextFlow, /// How the frame and its text fit each other (Auto Size, Shrink Text to Fit). #[serde(skip_serializing_if = "crate::skip::is_default")] pub fit: AreaFit, @@ -150,6 +166,7 @@ impl Default for AreaOptions { first_baseline: FirstBaseline::Ascent, first_baseline_min: 0.0, vertical_align: VerticalAlign::Top, + flow: TextFlow::Columns, fit: AreaFit::None, } } diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 0e3aea70e9..b5bc7e0654 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -25,9 +25,12 @@ pub struct CharStyle { /// Tracking in 1/1000 em. #[serde(default)] pub tracking: f64, - /// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em. + /// Manual pair spacing in 1/1000 em; None uses the automatic mode. #[serde(default, skip_serializing_if = "Option::is_none")] pub kerning: Option, + /// Use glyph shapes for automatic pair spacing; false uses font metrics. + #[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")] + pub optical_kerning: bool, #[serde(default)] pub baseline_shift: f64, #[serde(default = "hundred")] @@ -101,21 +104,55 @@ pub struct CharStyle { /// #[serde(default, rename = "tateChuYoko", skip_serializing_if = "crate::skip::is_default")] pub tate_chu_yoko: bool, + /// Standard Vertical Roman Alignment (Character panel menu, East Asian options): in vertical + /// type the half-width characters among these (Latin letters, digits and other characters that + /// would lie on their side) stand upright one below the other instead of being rotated + /// individually. Spaces and tate-chu-yoko blocks do not change, and horizontal type keeps the + /// mark and does not change. + /// + #[serde(default, rename = "standardVerticalRoman", skip_serializing_if = "crate::skip::is_default")] + pub standard_vertical_roman: bool, /// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of /// these characters are drawn in, whatever digits were typed. #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub digits: Digits, + /// Font height reference (Character panel menu › Show Font Height Options): the height of the + /// font that [`Self::size`] measures, the em box by default. + #[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")] + pub font_height_reference: FontHeightReference, /// No Break (Character panel menu): these characters are not broken across lines, including /// at a space or a hyphenation point inside the run. A run longer than the line stays together /// and can overflow it. /// #[serde(default, rename = "noBreak", skip_serializing_if = "crate::skip::is_default")] pub no_break: bool, + /// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these + /// characters are shaped in, so that the font uses that language's forms (OpenType `locl`). + /// `None`: the default language, English: USA, shaped without a language. New type takes the + /// document's language (Document Setup). Saved only when set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub language: Option, +} + +/// What a character's font size measures ([`CharStyle::font_height_reference`]): the em square +/// of the font, the height of its capitals or of its lowercase letters (the cap height and x +/// height of its OS/2 table), or its ideographic character face (ICF, OpenType's `icfb` and +/// `icft` baselines). Layout sets the characters at the em size at which the chosen height equals +/// the font size; with a font that has no such value, the size measures the em box. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FontHeightReference { + #[default] + EmBox, + CapHeight, + XHeight, + IcfBox, } /// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of -/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them. The text keeps -/// the digits that were typed; only the glyphs change (like All Caps). +/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them or in the digits +/// of an Indic script. The text keeps the digits that were typed; only the glyphs change (like +/// All Caps). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Digits { @@ -128,9 +165,68 @@ pub enum Digits { Hindi, /// Eastern Arabic-Indic digits ۰–۹ (U+06F0–U+06F9), used in Persian and Urdu. Farsi, + /// Devanagari digits ०–९ (U+0966–U+096F), used in Hindi, Marathi, Nepali and Sanskrit. + Devanagari, + /// Bengali digits ০–৯ (U+09E6–U+09EF), used in Bengali and Assamese. + Bengali, + /// Gurmukhi digits ੦–੯ (U+0A66–U+0A6F), used in Punjabi. + Gurmukhi, + /// Gujarati digits ૦–૯ (U+0AE6–U+0AEF). + Gujarati, + /// Odia digits ୦–୯ (U+0B66–U+0B6F). + Odia, + /// Tamil digits ௦–௯ (U+0BE6–U+0BEF). + Tamil, + /// Telugu digits ౦–౯ (U+0C66–U+0C6F). + Telugu, + /// Kannada digits ೦–೯ (U+0CE6–U+0CEF). + Kannada, + /// Malayalam digits ൦–൯ (U+0D66–U+0D6F). + Malayalam, } impl Digits { + /// Every numeral system, in menu order. + pub const ALL: [Digits; 13] = [ + Digits::Default, + Digits::Arabic, + Digits::Hindi, + Digits::Farsi, + Digits::Devanagari, + Digits::Bengali, + Digits::Gurmukhi, + Digits::Gujarati, + Digits::Odia, + Digits::Tamil, + Digits::Telugu, + Digits::Kannada, + Digits::Malayalam, + ]; + + /// The name files and commands give this numeral system (as it is saved). + pub fn id(self) -> &'static str { + match self { + Digits::Default => "default", + Digits::Arabic => "arabic", + Digits::Hindi => "hindi", + Digits::Farsi => "farsi", + Digits::Devanagari => "devanagari", + Digits::Bengali => "bengali", + Digits::Gurmukhi => "gurmukhi", + Digits::Gujarati => "gujarati", + Digits::Odia => "odia", + Digits::Tamil => "tamil", + Digits::Telugu => "telugu", + Digits::Kannada => "kannada", + Digits::Malayalam => "malayalam", + } + } + + /// The numeral system [`Digits::id`] names; `None` for any other name. + pub fn from_id(id: &str) -> Option { + Digits::ALL.into_iter().find(|d| d.id() == id) + } + /// The digit `c` is drawn as in this numeral system: the same digit in the chosen set, or `c` /// itself when `c` isn't a digit of the Western, Arabic-Indic or Eastern Arabic-Indic set. pub fn map(self, c: char) -> char { @@ -145,6 +241,15 @@ impl Digits { Digits::Arabic => '0' as u32, Digits::Hindi => 0x660, Digits::Farsi => 0x6F0, + Digits::Devanagari => 0x966, + Digits::Bengali => 0x9E6, + Digits::Gurmukhi => 0xA66, + Digits::Gujarati => 0xAE6, + Digits::Odia => 0xB66, + Digits::Tamil => 0xBE6, + Digits::Telugu => 0xC66, + Digits::Kannada => 0xCE6, + Digits::Malayalam => 0xD66, }; char::from_u32(base + value).unwrap_or(c) } @@ -266,6 +371,7 @@ impl Default for CharStyle { leading: None, tracking: 0.0, kerning: None, + optical_kerning: false, baseline_shift: 0.0, h_scale: 100.0, v_scale: 100.0, @@ -290,9 +396,12 @@ impl Default for CharStyle { char_direction: None, proportional_metrics: false, tate_chu_yoko: false, + standard_vertical_roman: false, small_caps: None, digits: Digits::Default, + font_height_reference: FontHeightReference::EmBox, no_break: false, + language: None, } } } diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 47106d7882..b66795e890 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -223,6 +223,7 @@ impl ParaList { position: CharPosition::Normal, tracking: 0.0, kerning: None, + optical_kerning: first.optical_kerning, tate_chu_yoko: false, underline: false, strikethrough: false, diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 54142efd7f..04deae8ee3 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -60,6 +60,69 @@ fn digits_map_between_the_numeral_systems() { assert_eq!(serde_json::from_value::(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi); } +/// The font height reference is the em box by default and is saved only when it is another. +#[test] +fn font_height_reference_is_saved_only_when_not_the_em_box() { + let st = CharStyle::default(); + assert_eq!(st.font_height_reference, FontHeightReference::EmBox); + assert!(serde_json::to_value(&st).unwrap().get("fontHeightReference").is_none()); + for (r, key) in + [(FontHeightReference::CapHeight, "capHeight"), (FontHeightReference::XHeight, "xHeight"), (FontHeightReference::IcfBox, "icfBox")] + { + let set = CharStyle { font_height_reference: r, ..CharStyle::default() }; + assert_eq!(serde_json::to_value(&set).unwrap()["fontHeightReference"], key); + assert_eq!(serde_json::from_value::(serde_json::to_value(&set).unwrap()).unwrap(), set); + } + // Styles written before the attribute existed read as the em box. + let old = serde_json::to_value(&st).unwrap(); + assert_eq!(serde_json::from_value::(old).unwrap().font_height_reference, FontHeightReference::EmBox); +} + +/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its +/// script's block; every system saves under its id, which reads back, and other names are refused. +#[test] +fn indic_digits_map_to_their_scripts_block() { + let map = |d: Digits, s: &str| -> String { s.chars().map(|c| d.map(c)).collect() }; + for (d, zero) in [ + (Digits::Devanagari, 0x966), + (Digits::Bengali, 0x9E6), + (Digits::Gurmukhi, 0xA66), + (Digits::Gujarati, 0xAE6), + (Digits::Odia, 0xB66), + (Digits::Tamil, 0xBE6), + (Digits::Telugu, 0xC66), + (Digits::Kannada, 0xCE6), + (Digits::Malayalam, 0xD66), + ] { + let block: String = (zero..zero + 10).map(|u| char::from_u32(u).unwrap()).collect(); + assert!(block.chars().all(char::is_numeric), "{d:?}: {block}"); + for s in ["0123456789", "٠١٢٣٤٥٦٧٨٩", "۰۱۲۳۴۵۶۷۸۹"] { + assert_eq!(map(d, s), block, "{d:?}"); + } + assert_eq!(map(d, "a-Z ٪"), "a-Z ٪"); + } + assert_eq!(map(Digits::Devanagari, "page 12"), "page १२"); + for d in Digits::ALL { + assert_eq!(serde_json::to_value(d).unwrap(), d.id()); + assert_eq!(serde_json::from_value::(d.id().into()).unwrap(), d); + assert_eq!(Digits::from_id(d.id()), Some(d)); + } + assert_eq!(Digits::from_id("roman"), None); + assert!(serde_json::from_value::("roman".into()).is_err()); +} + +/// Language is saved only when set; styles written before it existed read as the default. +#[test] +fn language_is_saved_only_when_set() { + let st = CharStyle::default(); + let old = serde_json::to_value(&st).unwrap(); + assert!(old.get("language").is_none()); + assert_eq!(serde_json::from_value::(old).unwrap().language, None); + let turkish = CharStyle { language: Some("tr".into()), ..CharStyle::default() }; + assert_eq!(serde_json::to_value(&turkish).unwrap()["language"], "tr"); + assert_eq!(serde_json::from_value::(serde_json::to_value(&turkish).unwrap()).unwrap(), turkish); +} + /// Auto leading follows the paragraph's Auto Leading; a set leading doesn't. #[test] fn paragraph_effective_leading_follows_auto_leading() { @@ -248,6 +311,19 @@ fn paragraph_styles_split_merge_and_normalize() { assert_eq!(back.para_at(3).space_before, 4.0); } +/// Text Flow is saved only when by rows: area type by columns (the default) saves as it did before +/// the option, and files from before it read by columns; other values don't read. +#[test] +fn text_flow_is_saved_only_when_by_rows() { + let by_columns = serde_json::to_value(AreaOptions::default()).unwrap(); + assert!(by_columns.get("flow").is_none()); + assert_eq!(serde_json::from_value::(by_columns).unwrap().flow, TextFlow::Columns); + let by_rows = serde_json::to_value(AreaOptions { flow: TextFlow::Rows, ..AreaOptions::default() }).unwrap(); + assert_eq!(by_rows["flow"], "rows"); + assert_eq!(serde_json::from_value::(by_rows).unwrap().flow, TextFlow::Rows); + assert!(serde_json::from_value::(serde_json::json!({"flow": "diagonal"})).is_err()); +} + /// 120 × 40 area type at (40, 40), its text drawn at twice its size. fn area_type() -> TextObject { let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 2c1fc86534..6a5edf75ac 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -161,7 +161,10 @@ impl Unit { /// A point value as the canvas measurement labels show it: two decimals and the suffix /// (`12.50 mm`). pub fn readout(self, pt: f64) -> String { - format!("{:.2} {}", self.from_pt(pt), self.suffix()) + let s = format!("{:.2}", self.from_pt(pt)); + // A small negative value rounds to `-0.00`; show it as `0.00`. + let s = if s == "-0.00" { "0.00" } else { &s }; + format!("{} {}", s, self.suffix()) } } diff --git a/crates/doc/src/variables.rs b/crates/doc/src/variables.rs index 96bccbd0a5..8656e216ce 100644 --- a/crates/doc/src/variables.rs +++ b/crates/doc/src/variables.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use super::{Document, NodeId, NodeKind}; +use super::{Document, NodeId, NodeKind, TextKind}; /// What a variable drives. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -117,7 +117,8 @@ pub struct Variables { #[serde(default, skip_serializing_if = "Option::is_none")] pub active_dataset: Option, /// Lock Variables: while set, variables can't be defined, deleted or renamed. Objects can - /// still be bound to them and unbound, and datasets still change and apply. + /// still be bound to them and unbound, and datasets still change and apply, except that an + /// import whose header would define a variable is refused. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub locked: bool, } @@ -202,17 +203,46 @@ impl Document { self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked))) } - /// What the object `id` holds for the variable of `kind`: its characters, whether it shows, - /// or a linked image's path. `None` when the object is gone, is not of that kind, has no - /// link path yet (an embedded image), or is locked or in a locked layer or group (the - /// document's value is whatever it was left at). + /// The type objects of the story that the type object `id` belongs to, in thread order: the + /// frames of its threaded text (area type and type on a path), else `id` alone. + pub fn story_of(&self, id: NodeId) -> Vec { + let frame = |f: &NodeId| matches!(self.node(*f).map(|n| &n.kind), Some(NodeKind::Text(t)) if !matches!(t.kind, TextKind::Point)); + match self.text_threads.iter().find(|thread| thread.contains(&id)) { + Some(thread) if frame(&id) => thread.iter().filter(|f| frame(f)).copied().collect(), + _ => vec![id], + } + } + + /// The characters of the story that the type object `id` belongs to ([`Document::story_of`]): + /// every frame's text joined in thread order. + pub fn story_text(&self, id: NodeId) -> String { + self.story_of(id) + .into_iter() + .filter_map(|f| match self.node(f).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => Some(t.plain_text()), + _ => None, + }) + .collect() + } + + /// Whether a data set reads and rewrites the text of the type object `id`: every frame of its + /// story ([`Document::story_of`]) is a [`Document::dataset_target`]. + pub fn story_target(&self, id: NodeId) -> bool { + self.story_of(id).into_iter().all(|f| self.dataset_target(f)) + } + + /// What the object `id` holds for the variable of `kind`: its characters (the whole story + /// for a frame of threaded text), whether it shows, or a linked image's path. `None` when the + /// object is gone, is not of that kind, has no link path yet (an embedded image), or is locked + /// or in a locked layer or group, or for text when a frame of its story is (the document's + /// value is whatever it was left at). pub fn variable_value(&self, id: NodeId, kind: VariableKind) -> Option { if !self.dataset_target(id) { return None; } let node = self.node(id)?; match (kind, &node.kind) { - (VariableKind::Text, NodeKind::Text(t)) => Some(DataValue::Text(t.plain_text())), + (VariableKind::Text, NodeKind::Text(_)) if self.story_target(id) => Some(DataValue::Text(self.story_text(id))), (VariableKind::Visibility, _) => Some(DataValue::Visible(node.visible)), (VariableKind::Image, NodeKind::Image(im)) => im.link.as_ref().map(|l| DataValue::Image(l.path.clone())), (VariableKind::Graph, _) => node.extras().graph.as_ref().map(|g| DataValue::Graph(g.to_csv())), diff --git a/crates/effects/src/addons.rs b/crates/effects/src/addons.rs new file mode 100644 index 0000000000..10c5977bf1 --- /dev/null +++ b/crates/effects/src/addons.rs @@ -0,0 +1,15 @@ +//! Effects of VectorCraft's built-in add-ons, one module per add-on. +//! +//! - [`color`]: Color Effects' live Exposure, Desaturate and Invert Colors, colour adjustments +//! evaluated with the others ([`crate::adjust`]). +//! - [`duotone`]: Color Effects' live Duotone, a colour adjustment that prints each colour's tone +//! with one to four inks. +//! - [`halftone`]: Color Effects' live Vector Halftone, and the screens Object › Vector Halftone +//! builds its dots with. +//! - [`path`]: Path Precision Tools' live Path Effects, geometry effects built on the add-on's path +//! kernels. + +pub mod color; +pub mod duotone; +pub mod halftone; +pub mod path; diff --git a/crates/effects/src/addons/color.rs b/crates/effects/src/addons/color.rs new file mode 100644 index 0000000000..07627dd8d7 --- /dev/null +++ b/crates/effects/src/addons/color.rs @@ -0,0 +1,138 @@ +//! Color Effects (a built-in add-on): live Exposure, Desaturate, Duotone and Invert Colors, in +//! Effect › Color Effects. They are colour adjustments ([`crate::is_adjustment`]): they recolour what +//! an object paints as the others do, in stack order with them. + +use serde_json::{Value, json}; + +use crate::catalog::{EffectInfo, Lengths}; +use crate::util::num; + +/// Exposure: brighten or darken in stops of light, with an offset and a gamma. +pub const EXPOSURE: &str = "addon.color.exposure"; +/// Desaturate: every colour to the grey of its lightness. +pub const DESATURATE: &str = "addon.color.desaturate"; +/// Invert Colors: every colour to its RGB inverse. +pub const INVERT: &str = "addon.color.invert"; +pub use super::duotone::DUOTONE; + +/// The add-on's effects, in menu order. +pub const EFFECTS: [&str; 4] = [DESATURATE, DUOTONE, EXPOSURE, INVERT]; + +/// Is `id` one of the add-on's effects? +pub fn is_color_effect(id: &str) -> bool { + EFFECTS.contains(&id) +} + +/// The add-on's catalogue entries. +pub(crate) fn catalog() -> Vec { + const MENU: &[&str] = &["Effect", "Color Effects"]; + let e = |id, label, params, defaults| EffectInfo { id, label, menu: MENU, params, defaults, raster: false, lengths: Lengths::default() }; + vec![ + e(DESATURATE, "Desaturate", "{} turns every colour the object paints to the grey of its lightness (each colour keeps its model)", json!({})), + e(DUOTONE, "Duotone…", super::duotone::PARAMS, super::duotone::defaults()), + e( + EXPOSURE, + "Exposure…", + "{exposure: stops -20..20 (0; mostly the highlights: each stop doubles or halves the light), offset: -0.5..0.5 (0; lifts or sinks the shadows and midtones), gamma: 0.1..10 (1; above 1 lightens the midtones)} recolours as Brightness/Contrast does, in linear light", + json!({"exposure": 0.0, "offset": 0.0, "gamma": 1.0}), + ), + e(INVERT, "Invert Colors", "{} turns every colour the object paints to its RGB inverse (each colour keeps its model)", json!({})), + ] +} + +/// One of the add-on's adjustments, its parameters normalised. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Adjust { + /// Linear light times `gain`, plus `offset`, to the power 1 / `gamma`. + Exposure { + gain: f32, + offset: f32, + gamma: f32, + }, + Desaturate, + Invert, + /// Duotone ([`super::duotone`]). + Duotone(super::duotone::Duotone), +} + +impl Adjust { + pub(crate) fn parse(id: &str, p: &Value) -> Option { + Some(match id { + EXPOSURE => Adjust::Exposure { + gain: 2f64.powf(num(p, "exposure", 0.0).clamp(-20.0, 20.0)) as f32, + offset: num(p, "offset", 0.0).clamp(-0.5, 0.5) as f32, + gamma: num(p, "gamma", 1.0).clamp(0.1, 10.0) as f32, + }, + DESATURATE => Adjust::Desaturate, + INVERT => Adjust::Invert, + DUOTONE => Adjust::Duotone(super::duotone::Duotone::parse(p)?), + _ => return None, + }) + } + + pub(crate) fn apply(&self, rgb: [f32; 3]) -> [f32; 3] { + match self { + Adjust::Exposure { gain, offset, gamma } => rgb.map(|v| to_srgb((to_linear(v) * gain + offset).max(0.0).powf(1.0 / gamma))), + Adjust::Desaturate => { + let [r, g, b] = rgb; + [(r.max(g).max(b) + r.min(g).min(b)) / 2.0; 3] + } + Adjust::Invert => rgb.map(|v| 1.0 - v), + Adjust::Duotone(d) => d.apply_rgb(rgb), + } + } +} + +fn to_linear(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +fn to_srgb(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::color_map; + use vectorcraft_doc::Effect; + + fn map(id: &str, params: Value) -> crate::ColorMap { + color_map(&[Effect { id: id.into(), params, visible: true }]).unwrap() + } + + fn close(a: [f32; 3], b: [f32; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01) + } + + #[test] + fn the_effects_are_colour_adjustments_in_their_own_menu() { + for id in EFFECTS { + assert!(crate::is_adjustment(id), "{id}"); + assert_eq!(crate::effect_info(id).unwrap().menu, ["Effect", "Color Effects"]); + } + } + + #[test] + fn exposure_works_in_stops_of_linear_light() { + let grey = [0.5; 3]; + assert!(close(map(EXPOSURE, json!({})).apply_rgb(grey), grey), "neutral by default"); + // One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686. + assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3])); + assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3])); + assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows"); + assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6); + assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped"); + } + + #[test] + fn desaturate_and_invert() { + assert!(close(map(DESATURATE, json!({})).apply_rgb([1.0, 0.0, 0.0]), [0.5; 3])); + assert!(close(map(DESATURATE, json!({})).apply_rgb([1.0, 1.0, 0.0]), [0.5; 3]), "lightness is kept, not luminance"); + assert!(close(map(INVERT, json!({})).apply_rgb([1.0, 0.25, 0.0]), [0.0, 0.75, 1.0])); + let both = map(INVERT, json!({})).then(&map(INVERT, json!({}))); + assert!(close(both.apply_rgb([0.2, 0.4, 0.6]), [0.2, 0.4, 0.6])); + } +} diff --git a/crates/effects/src/addons/duotone.rs b/crates/effects/src/addons/duotone.rs new file mode 100644 index 0000000000..c4febd8658 --- /dev/null +++ b/crates/effects/src/addons/duotone.rs @@ -0,0 +1,178 @@ +//! Color Effects' Duotone (Effect › Color Effects › Duotone…), a colour adjustment: the +//! grey-equivalent tone of each colour an object paints is printed with one to four inks (a +//! monotone, duotone, tritone or quadtone). Each ink, a tone, is a colour, typically a spot swatch, +//! with its own curve from the tone's tint to the ink's. The inks overprint, so their tints +//! multiply. +//! +//! With one tone of a swatch, a colour becomes a tint of that swatch, linked to it, so a spot tone +//! separates onto its plate. With several tones it becomes the CMYK mix of their tints: a colour +//! links to one swatch at one tint, and a mix of several spot inks has no swatch to link to. + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::Document; +use vectorcraft_doc::color::{Color, cms::Model}; + +use crate::adjust::{LUT, curve_at, curve_points_on, lookup, sample}; +use crate::raster::color_param; +use crate::util::flag; + +/// Duotone (Effect › Color Effects › Duotone…). +pub const DUOTONE: &str = "addon.color.duotone"; + +/// Most tones Duotone reads (a quadtone): any past them are left out. +pub const MAX_TONES: usize = 4; + +/// Most points a tone's curve reads: any past them are left out. +pub const MAX_CURVE_POINTS: usize = 64; + +/// The parameters' description (`effect.apply`). +pub(crate) const PARAMS: &str = "{tones: [{color: \"#rrggbb\" or a colour object, swatch?: a global or spot swatch's name (with the swatch's colour as `color`), curve?: \"tint,ink tint,ink …\" or [[tint, ink], …] (0..100, at most 64 points; \"0,0 100,100\"), active?: true}] (up to four inks, overprinting; any past four are left out), skipSpot?: false (colours linked to a spot swatch keep their colour)} prints the grey-equivalent tone of each colour the object paints with the inks, each at the tint its curve gives for the tone's: with one tone of a swatch, as a tint of that swatch (a spot tone prints on its own plate); with several, as the CMYK mix of their tints"; + +/// The dialog's defaults: one black tone, its curve linear. +pub(crate) fn defaults() -> Value { + json!({"tones": [{"color": "#000000", "curve": "0,0 100,100", "active": true}], "skipSpot": false}) +} + +/// Whether swatch `name` of the document is a spot colour: `Some(false)` for a global process +/// swatch, `None` when the document has no global swatch of that name. +pub type SwatchKinds<'a> = dyn Fn(&str) -> Option + 'a; + +/// [`SwatchKinds`] of `d`'s swatch `name`. +pub fn swatch_kind(d: &Document, name: &str) -> Option { + d.swatches_iter().find(|w| w.global && w.name == name).map(|w| w.spot) +} + +/// [`swatch_kind`] of each of `d`'s global swatches. +pub fn swatch_kinds(d: &Document) -> HashMap { + d.swatches_iter().filter(|w| w.global).map(|w| (w.name.clone(), w.spot)).collect() +} + +/// A tone's curve points (0..1 each) from its `curve` (0..100). +pub fn tone_curve_points(v: Option<&Value>) -> Vec<(f32, f32)> { + curve_points_on(v, 100.0, MAX_CURVE_POINTS) +} + +/// One ink. +#[derive(Clone, Debug, PartialEq)] +struct Tone { + color: Color, + /// `color` as CMYK inks, which several tones mix in. + cmyk: [f32; 4], + /// The swatch the colour is of, if any. + swatch: Option, + /// Its curve, sampled: the tone's tint → the ink's. + curve: Arc<[f32]>, +} + +/// Duotone's tones and options, its parameters read. +#[derive(Clone, Debug, PartialEq)] +pub struct Duotone { + tones: Vec, + skip_spot: bool, + /// The display colour at each sampled tint, for pixels. + rgb: Arc<[[f32; 3]]>, +} + +impl Duotone { + /// `None` without an active tone (the effect then leaves the colours as they are). + pub(crate) fn parse(p: &Value) -> Option { + let tones: Vec = p + .get("tones") + .and_then(Value::as_array) + .into_iter() + .flatten() + .take(MAX_TONES) + .filter(|t| t.is_object() && flag(t, "active", true)) + .map(|t| { + let color = finite(color_param(t, Color::BLACK)); + let cmyk = match color.in_model(Model::Cmyk) { + Color::Cmyk { c, m, y, k } => [c, m, y, k].map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }), + _ => [0.0, 0.0, 0.0, 1.0], + }; + let pts = tone_curve_points(t.get("curve")); + let swatch = t.get("swatch").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string); + Tone { color, cmyk, swatch, curve: sample(|x| curve_at(&pts, x)) } + }) + .collect(); + if tones.is_empty() { + return None; + } + let mut d = Duotone { tones, skip_spot: flag(p, "skipSpot", false), rgb: Arc::new([]) }; + d.rgb = (0..LUT).map(|i| d.mix(i as f32 / (LUT - 1) as f32).to_rgb()).collect(); + Some(d) + } + + /// The inks' colour for tone `t` (0 = white, 1 = black): one tone's colour at its tint, or + /// several tones' CMYK tints overprinted (each ink lets through what the others leave). + fn mix(&self, t: f32) -> Color { + if let [one] = self.tones.as_slice() { + return one.color.tinted(lookup(&one.curve, t)); + } + let mut paper = [1.0f32; 4]; + for tone in &self.tones { + let k = lookup(&tone.curve, t); + for (p, ink) in paper.iter_mut().zip(tone.cmyk) { + *p *= 1.0 - ink * k; + } + } + let [c, m, y, k] = paper.map(|p| 1.0 - p); + Color::cmyk(c, m, y, k) + } + + /// Display components 0..1 through the effect. + pub(crate) fn apply_rgb(&self, rgb: [f32; 3]) -> [f32; 3] { + let x = tone(rgb) * (LUT - 1) as f32; + let i = (x.floor() as usize).min(LUT - 2); + let f = x - i as f32; + match (self.rgb.get(i), self.rgb.get(i + 1)) { + (Some(a), Some(b)) => std::array::from_fn(|k| a[k] + (b[k] - a[k]) * f), + _ => rgb, + } + } + + /// A colour with its swatch link and tint through the effect ([`crate::ColorMap::apply_link`]): + /// true when it changed. With `skipSpot`, a colour linked to a spot swatch stays. + pub(crate) fn map_link(&self, c: &mut Color, link: &mut Option, tint: &mut f32, swatches: &SwatchKinds) -> bool { + if self.skip_spot && link.as_deref().and_then(swatches) == Some(true) { + return false; + } + let t = tone(c.to_rgb()); + let new = self.mix(t); + let (new_link, new_tint) = match self.tones.as_slice() { + [one] => match one.swatch.as_ref().filter(|n| swatches(n).is_some()) { + Some(name) => (Some(name.clone()), lookup(&one.curve, t)), + None => (None, 1.0), + }, + _ => (None, 1.0), + }; + if new == *c && new_link == *link && new_tint == *tint { + return false; + } + (*c, *link, *tint) = (new, new_link, new_tint); + true + } +} + +/// The grey-equivalent tone of display colour `rgb`: 0 for white, 1 for black (its luma, as +/// Convert to Grayscale reads it, so a grey's tone is its ink). +fn tone([r, g, b]: [f32; 3]) -> f32 { + let t = 1.0 - (0.299 * r + 0.587 * g + 0.114 * b); + if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 } +} + +/// `c` with its components finite and in range. +fn finite(c: Color) -> Color { + let v = |x: f32, lo: f32, hi: f32| if x.is_finite() { x.clamp(lo, hi) } else { lo }; + match c { + Color::Rgb { r, g, b } => Color::rgb(v(r, 0.0, 1.0), v(g, 0.0, 1.0), v(b, 0.0, 1.0)), + Color::Cmyk { c, m, y, k } => Color::cmyk(v(c, 0.0, 1.0), v(m, 0.0, 1.0), v(y, 0.0, 1.0), v(k, 0.0, 1.0)), + Color::Gray { k } => Color::gray(v(k, 0.0, 1.0)), + Color::Lab { l, a, b } => Color::lab(v(l, 0.0, 100.0), v(a, -128.0, 127.0), v(b, -128.0, 127.0)), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/effects/src/addons/duotone/tests.rs b/crates/effects/src/addons/duotone/tests.rs new file mode 100644 index 0000000000..8a3255b054 --- /dev/null +++ b/crates/effects/src/addons/duotone/tests.rs @@ -0,0 +1,128 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::Effect; +use vectorcraft_doc::color::Color; + +use super::*; +use crate::{ColorMap, color_map}; + +fn map(params: Value) -> ColorMap { + color_map(&[Effect { id: DUOTONE.into(), params, visible: true }]).unwrap() +} + +/// `c` with link `link` through `m`, the document having spot swatch "Ink" and process swatch +/// "Blue": (colour, link, tint, changed). +fn linked(m: &ColorMap, c: Color, link: Option<&str>) -> (Color, Option, f32, bool) { + let (mut c, mut link, mut tint) = (c, link.map(str::to_string), 1.0); + let kinds = |n: &str| match n { + "Ink" => Some(true), + "Blue" => Some(false), + _ => None, + }; + let changed = m.apply_link(&mut c, &mut link, &mut tint, &kinds); + (c, link, tint, changed) +} + +fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 0.01 +} + +fn looks(c: Color, rgb: [f32; 3]) -> bool { + c.to_rgb().iter().zip(rgb).all(|(a, b)| close(*a, b)) +} + +const INK: Color = Color::Cmyk { c: 0.0, m: 0.5, y: 1.0, k: 0.0 }; + +fn ink_tone(curve: &str) -> Value { + json!({"tones": [{"color": INK, "swatch": "Ink", "curve": curve}]}) +} + +#[test] +fn a_spot_tone_turns_greys_into_tints_of_its_swatch() { + let m = map(ink_tone("0,0 100,100")); + for k in [0.0, 0.25, 0.6, 1.0] { + let (c, link, tint, _) = linked(&m, Color::gray(k), None); + assert_eq!(link.as_deref(), Some("Ink"), "linked at {k}"); + assert!(close(tint, k), "the tint is the grey's ink: {k} → {tint}"); + assert_eq!(c, INK.tinted(tint), "its colour is the swatch's at that tint"); + } + // A colour reads as its grey equivalent: white is no ink. + let (_, _, tint, _) = linked(&m, Color::rgb(1.0, 1.0, 1.0), None); + assert!(close(tint, 0.0)); + // A swatch the document hasn't: an unlinked tint of the tone's colour. + let (c, link, ..) = linked(&map(json!({"tones": [{"color": INK, "swatch": "Gone"}]})), Color::gray(0.5), None); + assert!(link.is_none() && looks(c, INK.tinted(0.5).to_rgb())); + // Without the links, colours (mesh points) take the tone's colour too. + assert!(looks(m.apply(Color::gray(0.5)), INK.tinted(0.5).to_rgb())); +} + +#[test] +fn the_curve_changes_the_mapping() { + // Inverse: dark greys get little ink. + let (_, _, tint, _) = linked(&map(ink_tone("0,100 100,0")), Color::gray(0.8), None); + assert!(close(tint, 0.2), "{tint}"); + // Through its points exactly, flat past its ends. + let lifted = map(ink_tone("0,0 50,80 100,100")); + assert!(close(linked(&lifted, Color::gray(0.5), None).2, 0.8)); + assert!(close(linked(&map(ink_tone("20,0 80,100")), Color::gray(0.1), None).2, 0.0)); + // Unreadable or missing curves are linear; points past the cap are left out. + for curve in [json!("junk"), json!(null), json!([[0, 0]])] { + let p = json!({"tones": [{"color": INK, "swatch": "Ink", "curve": curve}]}); + assert!(close(linked(&map(p), Color::gray(0.3), None).2, 0.3), "{curve}"); + } + let many: Vec<[f64; 2]> = (0..200).map(|i| [f64::from(i) / 2.0, 100.0 - f64::from(i) / 2.0]).collect(); + assert_eq!(tone_curve_points(Some(&json!(many))).len(), MAX_CURVE_POINTS); +} + +#[test] +fn several_tones_multiply_as_cmyk_inks() { + let cyan = json!({"color": {"model": "cmyk", "c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}, "swatch": "Ink"}); + let half_black = json!({"color": {"model": "cmyk", "c": 0.6, "m": 0.0, "y": 0.0, "k": 1.0}, "curve": "0,0 100,50"}); + let m = map(json!({"tones": [cyan, half_black]})); + let (c, link, tint, changed) = linked(&m, Color::gray(1.0), Some("Ink")); + assert!(changed && link.is_none() && tint == 1.0, "a process mix, unlinked"); + // Cyan 100% over the second ink at 50% (60% cyan, 100% black at half): cyan 1-(1-1)(1-0.3). + let Color::Cmyk { c, m: mg, y, k } = c else { panic!("CMYK: {c:?}") }; + assert!(close(c, 1.0) && close(mg, 0.0) && close(y, 0.0) && close(k, 0.5), "{c} {mg} {y} {k}"); + let (mid, ..) = linked(&m, Color::gray(0.5), None); + let Color::Cmyk { c, k, .. } = mid else { panic!("CMYK") }; + // Cyan 50% over the second ink at 25% (15% cyan, 25% black): 1 - 0.5 * 0.85 = 0.575. + assert!(close(c, 0.575) && close(k, 0.25), "{c} {k}"); + // Inactive tones and tones past the fourth don't count; none active leaves the colours. + let one = json!({"color": "#000000"}); + let off = json!({"color": "#ff0000", "active": false}); + let only_black = map(json!({"tones": [one, off, off, off, {"color": "#ff0000"}]})); + assert!(looks(only_black.apply(Color::gray(0.4)), [0.6; 3])); + assert!(color_map(&[Effect { id: DUOTONE.into(), params: json!({"tones": [off]}), visible: true }]).is_none()); + assert!(color_map(&[Effect { id: DUOTONE.into(), params: json!({"tones": "x"}), visible: true }]).is_none()); +} + +#[test] +fn skip_spot_keeps_spot_colours() { + let mut p = json!({"tones": [{"color": "#000000"}], "skipSpot": true}); + let m = map(p.clone()); + let spot = Color::cmyk(0.0, 1.0, 0.0, 0.0); + assert_eq!(linked(&m, spot, Some("Ink")), (spot, Some("Ink".to_string()), 1.0, false)); + // A process swatch's colour, and an unlinked one, still change. + assert!(linked(&m, spot, Some("Blue")).3); + assert!(linked(&m, spot, None).3); + p["skipSpot"] = json!(false); + assert!(linked(&map(p), spot, Some("Ink")).3); +} + +#[test] +fn pixels_and_other_adjustments_compose() { + let m = map(json!({"tones": [{"color": "#ff0000"}]})); + // A grey pixel half way: half way to red from white. + let px = m.apply_rgb([0.5, 0.5, 0.5]); + assert!(close(px[0], 1.0) && close(px[1], 0.5) && close(px[2], 0.5), "{px:?}"); + // Invert, then Duotone: white becomes full red. + let both = color_map(&[ + Effect { id: crate::addons::color::INVERT.into(), params: json!({}), visible: true }, + Effect { id: DUOTONE.into(), params: json!({"tones": [{"color": "#ff0000"}]}), visible: true }, + ]) + .unwrap(); + assert!(looks(both.apply(Color::WHITE), [1.0, 0.0, 0.0])); + // Out of range colours are brought into range. + let wild = map(json!({"tones": [{"color": [1e30, -5, 0.5]}]})); + assert!(looks(wild.apply(Color::gray(1.0)), [1.0, 0.0, 0.5])); +} diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs new file mode 100644 index 0000000000..9b5771e7bd --- /dev/null +++ b/crates/effects/src/addons/halftone.rs @@ -0,0 +1,489 @@ +//! Vector Halftone (Color Effects): the art as vector dots, lines or shapes sized by its tone, as a +//! live effect (Effect › Color Effects › Vector Halftone…, [`HALFTONE`]) and for Object › Vector +//! Halftone, which builds its paths with the same screens ([`Halftone::layers`]). +//! +//! The art is sampled from pixels ([`Samples`], drawn by the renderer) once per halftone cell on a +//! grid turned by the screen angle; each cell gets a shape whose area follows the tone there. Mono +//! screens follow lightness in one colour (or, with `fromArt`, each dot takes the art's colour under +//! it); CMYK screens follow the art's ink amounts (as CMYK output separates it), one screen per ink at +//! the classic angles, multiplied over each other. The dots can be clipped to the art's outline as +//! real geometry. +//! +//! The renderer, the exporters ([`crate::bake_document`]) and Expand Appearance draw an object with +//! the effect as [`halftone_art`]: the renderer samples the art, so it registers how ([`set_art`]). + +use std::collections::BTreeMap; +use std::sync::{Arc, OnceLock}; + +use serde_json::{Value, json}; +use vectorcraft_doc::color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; +use vectorcraft_pathops::{self as po, BoolOp}; + +use crate::catalog::{EffectInfo, Lengths}; +use crate::util::{flag, num, text}; + +/// Vector Halftone, the live effect. +pub const HALFTONE: &str = "addon.color.halftone"; + +/// Most halftone cells per screen. +pub const MAX_CELLS: f64 = 100_000.0; +/// Most pixels the tone is sampled from. +pub const MAX_SAMPLE_PIXELS: f64 = 16.0e6; +/// Cells lighter than this get no dot. +const MIN_TONE: f64 = 0.01; +/// Levels per channel the art's colours are rounded to with `fromArt` (one path per colour). +const COLOR_LEVELS: f64 = 15.0; + +/// The effect's catalogue entry. +pub(crate) fn catalog() -> Vec { + vec![EffectInfo { + id: HALFTONE, + label: "Vector Halftone…", + menu: &["Effect", "Color Effects"], + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), + raster: false, + lengths: Lengths::default(), + }] +} + +/// Does `n` carry a visible Vector Halftone effect? +pub fn has_halftone(n: &Node) -> bool { + n.appearance.effects.iter().any(|e| e.visible && e.id == HALFTONE) +} + +/// The shape of a halftone dot. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DotShape { + Circle, + Ellipse, + Square, + Diamond, + Line, +} + +impl DotShape { + pub fn parse(s: &str) -> Option { + Some(match s.to_ascii_lowercase().as_str() { + "circle" | "round" | "dot" => DotShape::Circle, + "ellipse" => DotShape::Ellipse, + "square" => DotShape::Square, + "diamond" => DotShape::Diamond, + "line" | "lines" => DotShape::Line, + _ => return None, + }) + } + + /// The shape for tone `t` (0..1) in a cell of side `s` centred on the origin, the screen + /// running along x. + fn path(self, t: f64, s: f64) -> PathData { + let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side))); + match self { + DotShape::Circle => { + let r = s * (t / std::f64::consts::PI).sqrt(); + shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r))) + } + DotShape::Ellipse => { + let r = s * (t / std::f64::consts::PI).sqrt(); + shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3))) + } + DotShape::Square => square(s * t.sqrt()), + DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), + // Cells along a row join into a line as thick as the tone. + DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), + } + } +} + +/// One screen: its ink and angle, and how to read its tone from a sampled pixel. +struct Screen { + paint: Color, + angle: f64, + /// Index into the sampled pixel (unused for mono, CMYK inks for cmyk). + channel: usize, +} + +/// The sampled art: `w`×`h` pixels of 4 bytes over `region` at `scale` px/pt. +pub struct Samples { + px: Vec, + w: usize, + h: usize, + region: Rect, + scale: f64, + /// Mono: tones are 1 − lightness of RGBA pixels drawn on white; CMYK: ink amounts. + mono: bool, + invert: bool, +} + +impl Samples { + /// Pixels `px` (`w`×`h`, 4 bytes each) over `region` at `scale` px/pt; `None` when there are + /// fewer bytes than that. + pub fn new(px: Vec, (w, h): (usize, usize), region: Rect, scale: f64, mono: bool, invert: bool) -> Option { + (px.len() >= w.checked_mul(h)?.checked_mul(4)?).then_some(Self { px, w, h, region, scale, mono, invert }) + } + + /// The index of the pixel at document point `p`, `None` outside the samples. + fn index(&self, p: Point) -> Option { + let x = ((p.x - self.region.x0) * self.scale).floor(); + let y = ((p.y - self.region.y0) * self.scale).floor(); + (x >= 0.0 && y >= 0.0 && (x as usize) < self.w && (y as usize) < self.h).then(|| (y as usize * self.w + x as usize) * 4) + } + + fn byte(&self, i: usize, k: usize) -> f64 { + self.px.get(i + k).copied().unwrap_or(0) as f64 / 255.0 + } + + /// The tone (0..1) of `channel` at document point `p`. + fn tone(&self, p: Point, channel: usize) -> f64 { + let Some(i) = self.index(p) else { return if self.invert { 1.0 } else { 0.0 } }; + let t = + if self.mono { 1.0 - (0.2126 * self.byte(i, 0) + 0.7152 * self.byte(i, 1) + 0.0722 * self.byte(i, 2)) } else { self.byte(i, channel) }; + if self.invert { 1.0 - t } else { t } + } + + /// The 3 × 3 sample points of a cell of side `s` at `c` turned by `rot`. + fn cell_points(c: Point, s: f64, rot: Affine) -> impl Iterator { + (0..9).map(move |k| c + (rot * Point::new((f64::from(k / 3) - 1.0) * s / 3.0, (f64::from(k % 3) - 1.0) * s / 3.0)).to_vec2()) + } + + /// The mean tone over a cell of side `s` at `c` turned by `rot` (3 × 3 samples). + fn cell_tone(&self, c: Point, s: f64, rot: Affine, channel: usize) -> f64 { + Self::cell_points(c, s, rot).map(|p| self.tone(p, channel)).sum::() / 9.0 + } + + /// The mean colour over a cell (as [`Self::cell_tone`]; white outside the samples), each channel + /// rounded to [`COLOR_LEVELS`] steps. + fn cell_color(&self, c: Point, s: f64, rot: Affine) -> [u8; 3] { + let mut sum = [0.0; 3]; + for p in Self::cell_points(c, s, rot) { + for (k, v) in sum.iter_mut().enumerate() { + *v += self.index(p).map_or(1.0, |i| self.byte(i, k)); + } + } + sum.map(|v| (v / 9.0 * COLOR_LEVELS).round().clamp(0.0, COLOR_LEVELS) as u8) + } +} + +/// A halftone's settings. +#[derive(Clone, Debug, PartialEq)] +pub struct Halftone { + pub shape: DotShape, + /// Lines per inch. + pub frequency: f64, + /// Degrees. + pub angle: f64, + /// One screen in `color` (else four CMYK screens). + pub mono: bool, + pub color: Color, + /// Mono: each dot in the art's colour under it instead of `color`. + pub from_art: bool, + /// Dots for light tones. + pub invert: bool, + /// The dots clipped to the art's outline. + pub clip: bool, +} + +impl Halftone { + /// The settings of `n`'s last visible Vector Halftone effect, its values brought into range. + pub fn of(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.visible && e.id == HALFTONE)?; + Some(Self::from_params(&e.params)) + } + + fn from_params(p: &Value) -> Self { + Self { + shape: DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), + frequency: num(p, "frequency", 20.0).clamp(1.0, 300.0), + angle: num(p, "angle", 45.0), + mono: !text(p, "mode", "mono").eq_ignore_ascii_case("cmyk"), + color: crate::raster::color_param(p, Color::BLACK), + from_art: flag(p, "fromArt", false), + invert: flag(p, "invert", false), + clip: flag(p, "clip", true), + } + } + + /// The side of a cell in points. + pub fn cell(&self) -> f64 { + 72.0 / self.frequency + } + + /// Where the art over `bounds` is sampled and at how many pixels per point: about four pixels per + /// cell, at most [`MAX_SAMPLE_PIXELS`]. `None` when `bounds` have no area or the grid turned by + /// the screen angle would have more than [`MAX_CELLS`] cells. + pub fn plan(&self, bounds: Rect) -> Option<(Rect, f64)> { + let cell = self.cell(); + if !(bounds.width() > 0.0 && bounds.height() > 0.0 && bounds.area().is_finite()) { + return None; + } + // The grid turned by the screen angle covers at most (w + h)² / 2. + if (bounds.width() + bounds.height()).powi(2) / 2.0 / (cell * cell) > MAX_CELLS { + return None; + } + let scale = (4.0 / cell).min((MAX_SAMPLE_PIXELS / bounds.area()).sqrt()).clamp(0.01, 16.0); + Some((bounds.inflate(cell, cell), scale)) + } + + /// The screens, bottom to top. + fn screens(&self) -> Vec { + let angle = self.angle; + if self.mono { + return vec![Screen { paint: self.color, angle, channel: 0 }]; + } + // Bottom to top: yellow, magenta, cyan, black. + vec![ + Screen { paint: Color::cmyk(0.0, 0.0, 1.0, 0.0), angle: angle - 45.0, channel: 2 }, + Screen { paint: Color::cmyk(0.0, 1.0, 0.0, 0.0), angle: angle + 30.0, channel: 1 }, + Screen { paint: Color::cmyk(1.0, 0.0, 0.0, 0.0), angle: angle - 30.0, channel: 0 }, + Screen { paint: Color::cmyk(0.0, 0.0, 0.0, 1.0), angle, channel: 3 }, + ] + } + + /// The dots of the art `samples` show over `bounds`, one path per ink (per colour with + /// `fromArt`) in paint order, each clipped to `outline` when given, and how many dots there are. + pub fn layers(&self, samples: &Samples, bounds: Rect, outline: Option<&(BezPath, FillRule)>) -> (Vec<(PathData, Color)>, usize) { + let cell = self.cell(); + let mut layers = vec![]; + let mut count = 0; + for sc in self.screens() { + let dots = screen_dots(samples, bounds, cell, &sc, self.shape); + count += dots.len(); + if self.mono && self.from_art { + let rot = Affine::rotate(sc.angle.to_radians()); + let mut by_color: BTreeMap<[u8; 3], Vec> = BTreeMap::new(); + for (dot, c) in dots { + by_color.entry(samples.cell_color(c, cell, rot)).or_default().push(dot); + } + for (rgb, dots) in by_color { + let [r, g, b] = rgb.map(|v| (f64::from(v) / COLOR_LEVELS) as f32); + layers.push((merged(dots, outline), Color::rgb(r, g, b))); + } + } else { + layers.push((merged(dots.into_iter().map(|d| d.0).collect(), outline), sc.paint)); + } + } + layers.retain(|(path, _)| !path.is_empty()); + (layers, count) + } +} + +/// The dots of one screen over `bounds`, each with its cell's centre. +fn screen_dots(samples: &Samples, bounds: Rect, cell: f64, sc: &Screen, shape: DotShape) -> Vec<(PathData, Point)> { + let rot = Affine::rotate(sc.angle.to_radians()); + let inv = rot.inverse(); + // The grid covers the bounds in screen space. + let corners = + [bounds.origin(), Point::new(bounds.x1, bounds.y0), Point::new(bounds.x1, bounds.y1), Point::new(bounds.x0, bounds.y1)].map(|q| inv * q); + let (mut lo, mut hi) = (corners[0], corners[0]); + for q in &corners[1..] { + lo = Point::new(lo.x.min(q.x), lo.y.min(q.y)); + hi = Point::new(hi.x.max(q.x), hi.y.max(q.y)); + } + let (i0, i1) = ((lo.x / cell).floor() as i64 - 1, (hi.x / cell).ceil() as i64 + 1); + let (j0, j1) = ((lo.y / cell).floor() as i64 - 1, (hi.y / cell).ceil() as i64 + 1); + let near = bounds.inflate(cell, cell); + let mut dots = vec![]; + for j in j0..=j1 { + for i in i0..=i1 { + let c = rot * Point::new((i as f64 + 0.5) * cell, (j as f64 + 0.5) * cell); + if !near.contains(c) { + continue; + } + let t = samples.cell_tone(c, cell, rot, sc.channel).clamp(0.0, 1.0); + if t < MIN_TONE { + continue; + } + let place = Affine::translate(c.to_vec2()) * rot; + dots.push((shape.path(t, cell).transformed(place), c)); + } + } + dots +} + +/// The outline Clip to Art clips the dots of `nodes` to: their clip outline taken together. +pub fn art_outline(nodes: &[Node]) -> Option<(BezPath, FillRule)> { + crate::clip_outline(&Node::group(NodeId(u64::MAX), nodes.iter().cloned().map(Arc::new).collect())) +} + +/// `dots` as one path, clipped to `outline` when given (dots wholly inside it need no clipping). +fn merged(dots: Vec, outline: Option<&(BezPath, FillRule)>) -> PathData { + let (mut inside, mut edge) = (vec![], vec![]); + for dot in dots { + let whole = match (outline, dot.control_bounds()) { + (Some((bp, rule)), Some(db)) => [db.origin(), Point::new(db.x1, db.y0), Point::new(db.x1, db.y1), Point::new(db.x0, db.y1)] + .iter() + .all(|q| fill_contains(bp, *rule, *q)), + _ => true, + }; + if whole { inside.push(dot) } else { edge.push(dot) } + } + let mut subs: Vec<_> = inside.into_iter().flat_map(|p| p.subpaths).collect(); + if let Some((bp, rule)) = outline + && !edge.is_empty() + { + let edge = PathData::new(edge.into_iter().flat_map(|p| p.subpaths).collect()); + let clipped = po::boolean(&edge, FillRule::NonZero, &PathData::from_bezpath(bp), *rule, BoolOp::Intersect); + subs.extend(clipped.subpaths); + } else { + subs.extend(edge.into_iter().flat_map(|p| p.subpaths)); + } + PathData::new(subs) +} + +/// The paths of `layers` ([`Halftone::layers`]), each filled with its ink and ids from `id`; CMYK +/// screens (`mono` false) multiply over each other. +pub fn dot_nodes(layers: Vec<(PathData, Color)>, mono: bool, id: &mut dyn FnMut() -> NodeId) -> Vec> { + layers + .into_iter() + .map(|(path, ink)| { + let mut n = Node::path(id(), path, Appearance::basic(Paint::solid(ink), Paint::None, 0.0)); + if !mono { + n.blend = BlendMode::Multiply; + } + Arc::new(n) + }) + .collect() +} + +/// `n` split for its halftone: the object the effect samples (`n` visible, without its Vector +/// Halftone effects, transparency, mask and link) and an empty group that takes over its identity, +/// transparency, mask and link, for the dots. +pub fn split(n: &Node) -> (Node, Node) { + let mut object = n.clone(); + object.appearance.effects.retain(|e| e.id != HALFTONE); + object.visible = true; + let mut g = Node::group(n.id, vec![]); + (g.visible, g.locked) = (n.visible, n.locked); + g.name = object.name.take(); + g.opacity = std::mem::replace(&mut object.opacity, 1.0); + g.blend = std::mem::take(&mut object.blend); + g.isolate = std::mem::take(&mut object.isolate); + g.extras_mut().mask = object.extras_mut().mask.take(); + g.extras_mut().attrs = object.extras_mut().attrs.take(); + (object, g) +} + +/// How far the dots of `n`'s halftone reach past the bounds of the object it samples: nothing when +/// they are clipped to its outline, else up to two cells (a dot's centre lies within a cell of the +/// bounds, and the dot within another). +pub fn reach(n: &Node) -> f64 { + Halftone::of(n).filter(|h| !h.clip).map_or(0.0, |h| 2.0 * h.cell()) +} + +/// Makes the art of an object with a visible Vector Halftone effect ([`halftone_art`]). +pub type ArtHook = fn(&Document, &Node) -> Option; + +static ART: OnceLock = OnceLock::new(); + +/// Register how the art of an object with Vector Halftone is made (the renderer samples it, above +/// this crate; the first registration stays). +pub fn set_art(f: ArtHook) { + // Already set: the same renderer, registered by another session. + let _ = ART.set(f); +} + +/// The art of `n` with a visible Vector Halftone effect in `d`: the group [`split`] makes, holding +/// the dot paths ([`dot_nodes`], ids `n`'s). `None` without the effect, while nothing is registered +/// ([`set_art`]), and when the art has no area or would take too many cells ([`Halftone::plan`]). +pub fn halftone_art(d: &Document, n: &Node) -> Option { + if !has_halftone(n) { + return None; + } + ART.get()?(d, n) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::Effect; + + /// A black square's samples: `side` points of black from (10, 10), white around it. + fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { + let b = Rect::new(10.0, 10.0, 10.0 + side, 10.0 + side); + let (region, scale) = h.plan(b).unwrap(); + let (w, hh) = ((region.width() * scale).round() as usize, (region.height() * scale).round() as usize); + let mut px = vec![255u8; w * hh * 4]; + for y in 0..hh { + for x in 0..w { + let p = Point::new(region.x0 + (x as f64 + 0.5) / scale, region.y0 + (y as f64 + 0.5) / scale); + if b.contains(p) { + px[(y * w + x) * 4..][..3].copy_from_slice(&[200, 0, 0]); + } + } + } + (Samples::new(px, (w, hh), region, scale, true, h.invert).unwrap(), b) + } + + fn effect(params: Value) -> Node { + let mut n = Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + n.appearance.effects.push(Effect { id: HALFTONE.into(), params, visible: true }); + n + } + + #[test] + fn the_effect_is_in_color_effects_with_its_defaults() { + let info = crate::effect_info(HALFTONE).unwrap(); + assert_eq!(info.menu, ["Effect", "Color Effects"]); + assert!(!crate::is_geometry(HALFTONE) && !crate::is_raster(HALFTONE) && !crate::is_adjustment(HALFTONE)); + let h = Halftone::of(&effect(info.defaults)).unwrap(); + assert_eq!((h.shape, h.frequency, h.angle, h.mono, h.from_art, h.invert, h.clip), (DotShape::Circle, 20.0, 45.0, true, false, false, true)); + assert_eq!(h.color, Color::BLACK); + } + + #[test] + fn values_out_of_range_are_brought_in() { + let h = Halftone::of(&effect(json!({"frequency": 1e308, "angle": "NaN", "shape": 7, "mode": "CMYK", "color": "nope"}))).unwrap(); + assert_eq!((h.frequency, h.angle, h.shape, h.mono, h.color), (300.0, 45.0, DotShape::Circle, false, Color::BLACK)); + assert_eq!(Halftone::of(&effect(json!({"frequency": -5}))).unwrap().frequency, 1.0); + let mut hidden = effect(json!({})); + hidden.appearance.effects[0].visible = false; + assert!(Halftone::of(&hidden).is_none() && !has_halftone(&hidden)); + } + + #[test] + fn dots_follow_the_tone_and_the_settings() { + let h = Halftone::of(&effect(json!({"frequency": 18}))).unwrap(); + let (s, b) = black_square(60.0, &h); + let (layers, dots) = h.layers(&s, b, None); + assert_eq!(layers.len(), 1); + assert!((150..=320).contains(&dots), "{dots}"); + // Inverted, the dark square gets small dots and the white around it full ones. + let inv = Halftone { invert: true, ..h.clone() }; + let (s2, _) = black_square(60.0, &inv); + assert!(inv.layers(&s2, b, None).1 > dots); + // The colour of the art under each dot. + let art = Halftone { from_art: true, ..h.clone() }; + let (layers, _) = art.layers(&s, b, None); + assert!(layers.iter().any(|(_, c)| c.to_hex() == "#cc0000"), "{:?}", layers.iter().map(|l| l.1.to_hex()).collect::>()); + // CMYK screens: one layer per ink with dots (red: magenta and yellow). + let cmyk = Halftone { mono: false, ..h }; + let one = Samples::new([0u8, 255, 255, 0].repeat(400), (20, 20), Rect::new(0.0, 0.0, 20.0, 20.0), 1.0, false, false).unwrap(); + assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2); + } + + #[test] + fn the_caps_refuse_too_many_cells() { + let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap(); + assert!(h.plan(Rect::new(0.0, 0.0, 10_000.0, 10_000.0)).is_none()); + assert!(h.plan(Rect::new(0.0, 0.0, f64::INFINITY, 10.0)).is_none()); + assert!(h.plan(Rect::new(0.0, 0.0, 0.0, 10.0)).is_none()); + assert!(h.plan(Rect::new(0.0, 0.0, 40.0, 40.0)).is_some()); + assert!(Samples::new(vec![0; 3], (1, 1), Rect::new(0.0, 0.0, 1.0, 1.0), 1.0, true, false).is_none()); + assert!(Samples::new(vec![], (usize::MAX, 2), Rect::new(0.0, 0.0, 1.0, 1.0), 1.0, true, false).is_none()); + } + + #[test] + fn the_group_takes_the_objects_identity() { + let mut n = effect(json!({"clip": false, "frequency": 36})); + n.opacity = 0.5; + n.name = Some("art".into()); + let (object, g) = split(&n); + assert!(!has_halftone(&object)); + assert_eq!((object.opacity, g.opacity, g.id, g.name.as_deref()), (1.0, 0.5, n.id, Some("art"))); + assert_eq!(reach(&n), 4.0); + assert_eq!(reach(&effect(json!({}))), 0.0); + } +} diff --git a/crates/effects/src/addons/path.rs b/crates/effects/src/addons/path.rs new file mode 100644 index 0000000000..556122f636 --- /dev/null +++ b/crates/effects/src/addons/path.rs @@ -0,0 +1,243 @@ +//! Path Effects (Path Precision Tools): live geometry effects that rewrite an object's path with the +//! add-on's path kernels (Effect › Path Effects). Each is evaluated with the other geometry effects +//! ([`crate::apply_geometry`]), so it draws, measures, exports and expands as they do; the geometry +//! is written only by Expand Appearance. +//! +//! Parameters come from documents and scripts, so each is clamped to its documented range, and a +//! path with a coordinate past [`MAX_COORDINATE`] or not finite is left as it is. + +use serde_json::{Value, json}; +use vectorcraft_doc::Dash; +use vectorcraft_geom::{PathData, Point, SubPath}; +use vectorcraft_pathops::addons::pathtools::{self as tools, AnchorSpacing, CloseMode, ExtendMode, SMOOTH_RATIO, SegmentKind}; +use vectorcraft_pathops::addons::{PT_PER_TOLERANCE, retract_tiny_handles, simplify_keep_shape}; + +use crate::catalog::{EffectInfo, Lengths}; +use crate::stroke; +use crate::util::{flag, num, text}; + +/// What every Path Effect's id starts with. +pub const PREFIX: &str = "addon.path."; +pub const DASHES: &str = "addon.path.dashes"; +pub const ADD_ANCHORS: &str = "addon.path.addAnchors"; +pub const EXTEND: &str = "addon.path.extend"; +pub const CLOSE: &str = "addon.path.close"; +pub const SMOOTH: &str = "addon.path.smooth"; +pub const RETRACT: &str = "addon.path.retract"; +pub const REVERSE: &str = "addon.path.reverse"; +pub const SIMPLIFY: &str = "addon.path.simplify"; +pub const SPLIT: &str = "addon.path.split"; + +const MENU: &[&str] = &["Effect", "Path Effects"]; + +/// The dash and gap parameters of [`DASHES`], pair by pair. +const DASH_PAIRS: [(&str, &str); 5] = [("dash1", "gap1"), ("dash2", "gap2"), ("dash3", "gap3"), ("dash4", "gap4"), ("dash5", "gap5")]; +/// Longest dash or gap, and the farthest offset (pt). +const MAX_DASH: f64 = 10_000.0; +/// Longest stretch [`EXTEND`] adds or takes off an end, in points and in percent of the path. +const MAX_EXTEND: f64 = 100_000.0; +const MAX_EXTEND_PERCENT: f64 = 1000.0; +/// Most anchors [`ADD_ANCHORS`] adds to one segment. +const MAX_PER_SEGMENT: f64 = 1000.0; +/// Closest and farthest apart [`ADD_ANCHORS`]' anchors are (pt). +const DISTANCE_RANGE: (f64, f64) = (0.01, 100_000.0); +/// The range of [`SMOOTH`]'s ratio. +const RATIO_RANGE: (f64, f64) = (0.01, 0.5); +/// Longest handle length [`RETRACT`] takes (pt). +const MAX_HANDLE: f64 = 100_000.0; +/// Highest tolerance of [`SIMPLIFY`]. +const MAX_TOLERANCE: f64 = 200.0; +// shortcut: simplifying measures every anchor on every draw, so a larger path draws as it is; lift +// this if the kernel gets an incremental pass. +/// Most anchors [`SIMPLIFY`] takes in one path. +const MAX_SIMPLIFY_ANCHORS: usize = 50_000; +/// A path with a coordinate past this, or one that isn't finite, is left as it is: lengths measured +/// on it would overflow. +const MAX_COORDINATE: f64 = 1e12; + +/// The effects' catalogue entries. +pub(crate) fn catalog() -> Vec { + let entry = |id, label, params, defaults, always| EffectInfo { + id, + label, + menu: MENU, + params, + defaults, + raster: false, + lengths: Lengths { always, absolute: &[] }, + }; + vec![ + entry( + DASHES, + "Dashes to Geometry…", + "{dash1: pt 0..10000 (12), gap1: pt 0..10000 (6), dash2: pt 0..10000 (0), gap2: pt 0..10000 (0), dash3: pt 0..10000 (0), gap3: pt 0..10000 (0), dash4: pt 0..10000 (0), gap4: pt 0..10000 (0), dash5: pt 0..10000 (0), gap5: pt 0..10000 (0), offset: pt -10000..10000 (0; how far into the pattern the path starts; not with alignCorners), alignCorners: bool (false; every run between corners and path ends holds whole periods, stretched or squeezed to fit, with a dash centred on each corner and end)} cuts the path into its dashes, open subpaths along it that the stroke paints as it paints any path. A dash of 0 is a point its stroke's round or projecting cap paints; a pair of two zeros is left out, and the pattern repeats. A pattern of nothing, or of more than 200000 dashes, leaves the path as it is; a dash longer than a closed subpath keeps it closed", + json!({"dash1": 12.0, "gap1": 6.0, "dash2": 0.0, "gap2": 0.0, "dash3": 0.0, "gap3": 0.0, "dash4": 0.0, "gap4": 0.0, "dash5": 0.0, "gap5": 0.0, "offset": 0.0, "alignCorners": false}), + &["dash1", "gap1", "dash2", "gap2", "dash3", "gap3", "dash4", "gap4", "dash5", "gap5", "offset"], + ), + entry( + ADD_ANCHORS, + "Add Anchors…", + "{target: \"all\"|\"curved\"|\"straight\" (all; the segments that get anchors), spacing: \"count\"|\"distance\" (count), count: 1..1000 (1; anchors on each segment, evenly spaced by length), distance: pt 0.01..100000 (20; an anchor every so far along each segment from its start), maxCount: 1..1000 (100; most anchors added to one segment)} adds anchors without changing the shape; past 2 million anchors in all the path stays as it is", + json!({"target": "all", "spacing": "count", "count": 1, "distance": 20.0, "maxCount": 100}), + &["distance"], + ), + entry( + EXTEND, + "Extend Path…", + "{startLength: pt -100000..100000 (10), startPercent: % of the path's length -1000..1000 (0), startShape: \"straight\"|\"arc\" (straight), endLength: pt -100000..100000 (10), endPercent: % of the path's length -1000..1000 (0), endShape: \"straight\"|\"arc\" (straight)} lengthens each end of an open subpath by its length and percent together, or shortens it back along itself when they come to less than 0. Straight runs on along the end's direction; arc follows the circle of the end's curvature, at most half way round. Closed subpaths stay as they are, and so does an end that would be shortened to nothing", + json!({"startLength": 10.0, "startPercent": 0.0, "startShape": "straight", "endLength": 10.0, "endPercent": 0.0, "endShape": "straight"}), + &["startLength", "endLength"], + ), + entry( + CLOSE, + "Close Path…", + "{mode: \"straight\"|\"smooth\" (straight; smooth: the closing segment leaves both ends smoothly)} closes every open subpath of two anchors or more", + json!({"mode": "straight"}), + &[], + ), + entry( + SMOOTH, + "Smooth Anchors…", + "{ratio: 0.01..0.5 (0.3905; a handle's length as a share of the distance to the nearer neighbour; 0.3905 makes a square's corners a circle)} makes every anchor smooth: a lone handle is mirrored, two are brought into line keeping their lengths, and an anchor without handles gets them at right angles to the bisector of its neighbours", + json!({"ratio": SMOOTH_RATIO}), + &[], + ), + entry( + RETRACT, + "Retract Handles…", + "{handles: \"all\"|\"shorter\" (all; shorter: only those shorter than length), length: pt 0..100000 (5)} takes the handles back to their anchors; an anchor that loses one becomes a corner", + json!({"handles": "all", "length": 5.0}), + &["length"], + ), + entry( + REVERSE, + "Reverse Direction", + "{} runs every subpath the other way: the shape stays, and arrowheads, dashes and the effects after it swap ends", + json!({}), + &[], + ), + entry( + SIMPLIFY, + "Simplify Anchors…", + "{tolerance: 0..200 (10; higher removes more anchors and lets the outline move further, up to tolerance × 0.02 pt), protectCorners: bool (true; anchors where the path turns by more than 30° stay)} removes the anchors a path can do without, refitting the handles beside each; open ends stay; a path of more than 50000 anchors stays as it is", + json!({"tolerance": 10.0, "protectCorners": true}), + &[], + ), + entry( + SPLIT, + "Split at Anchors…", + "{anchors: \"corner\"|\"smooth\"|\"both\" (both; smooth: where the handles stand in line, corner: the others)} cuts subpaths into open pieces at those anchors; the shape stays, and an open path's ends aren't cuts", + json!({"anchors": "both"}), + &[], + ), + ] +} + +/// Path Effect `id` with parameters `p` on `path`, which keeps to `max` anchors where anchors are +/// added one by one. `path` as it is when `id` is no such effect or the path can't be measured. +pub(crate) fn apply(id: &str, p: &Value, path: &PathData, max: usize) -> PathData { + if !measurable(path) { + return path.clone(); + } + let edit = |change: &dyn Fn(&mut SubPath)| { + let mut out = path.clone(); + out.subpaths.iter_mut().for_each(change); + out + }; + match id { + DASHES => dashes(path, p), + ADD_ANCHORS => add_anchors(path, p, max).unwrap_or_else(|| path.clone()), + EXTEND => PathData::new(path.subpaths.iter().map(|sp| extend(sp, p)).collect()), + CLOSE => { + let mode = if text(p, "mode", "straight") == "smooth" { CloseMode::Smooth } else { CloseMode::Straight }; + edit(&|sp| { + tools::close(sp, mode, SMOOTH_RATIO); + }) + } + SMOOTH => { + let ratio = num(p, "ratio", SMOOTH_RATIO).clamp(RATIO_RANGE.0, RATIO_RANGE.1); + edit(&|sp| tools::smooth_anchors(sp, ratio)) + } + RETRACT if text(p, "handles", "all") == "shorter" => { + let length = num(p, "length", 5.0).clamp(0.0, MAX_HANDLE); + edit(&|sp| { + retract_tiny_handles(sp, length); + }) + } + RETRACT => edit(&|sp| sp.anchors.iter_mut().for_each(|a| a.retract())), + REVERSE => edit(&SubPath::reverse), + SIMPLIFY if path.anchor_count() <= MAX_SIMPLIFY_ANCHORS => { + let tolerance = num(p, "tolerance", 10.0).clamp(0.0, MAX_TOLERANCE) * PT_PER_TOLERANCE; + simplify_keep_shape(path, tolerance, flag(p, "protectCorners", true)) + } + SPLIT => { + let at = text(p, "anchors", "both"); + let (corners, smooth) = (at != "smooth", at != "corner"); + PathData::new(path.subpaths.iter().flat_map(|sp| tools::split_at_anchors(sp, corners, smooth)).collect()) + } + _ => path.clone(), + } +} + +/// Is every coordinate of `path` within [`MAX_COORDINATE`]? +fn measurable(path: &PathData) -> bool { + let near = |q: Point| q.x.abs() <= MAX_COORDINATE && q.y.abs() <= MAX_COORDINATE; + path.anchors().all(|(_, _, a)| near(a.p) && near(a.h_in) && near(a.h_out)) +} + +/// [`DASHES`]: the dashes of `path` as open subpaths, those of no length as subpaths that stay on +/// their point; `path` as it is when the pattern draws no dashes. +fn dashes(path: &PathData, p: &Value) -> PathData { + let length = |key| num(p, key, 0.0).clamp(0.0, MAX_DASH); + let pairs = DASH_PAIRS.iter().map(|(dash, gap)| (length(dash), length(gap))); + let pattern = pairs.filter(|(d, g)| *d > 0.0 || *g > 0.0).flat_map(|(d, g)| [d, g]).collect(); + let dash = Dash { pattern, offset: num(p, "offset", 0.0).clamp(-MAX_DASH, MAX_DASH), align_corners: flag(p, "alignCorners", false) }; + let Some(dashed) = stroke::dash(&path.to_bezpath(), &dash) else { return path.clone() }; + let mut out = PathData::from_bezpath(&dashed.path); + out.subpaths.extend(dashed.dots.iter().map(|d| SubPath::polyline(&[d.at, d.at], false))); + out +} + +/// [`ADD_ANCHORS`] within `max` anchors in all; `None` past them. +fn add_anchors(path: &PathData, p: &Value, max: usize) -> Option { + let which = match text(p, "target", "all") { + "curved" => SegmentKind::Curved, + "straight" => SegmentKind::Straight, + _ => SegmentKind::All, + }; + let spacing = match text(p, "spacing", "count") { + "distance" => AnchorSpacing::Distance(num(p, "distance", 20.0).clamp(DISTANCE_RANGE.0, DISTANCE_RANGE.1)), + _ => AnchorSpacing::Count(num(p, "count", 1.0).clamp(1.0, MAX_PER_SEGMENT) as usize), + }; + let cap = num(p, "maxCount", 100.0).clamp(1.0, MAX_PER_SEGMENT) as usize; + let mut room = max.saturating_sub(path.anchor_count()); + let mut out = Vec::with_capacity(path.subpaths.len()); + for sp in &path.subpaths { + let added = tools::add_anchors(sp, which, spacing, cap, room)?; + room = room.saturating_sub(added.anchors.len().saturating_sub(sp.anchors.len())); + out.push(added); + } + Some(PathData::new(out)) +} + +/// [`EXTEND`] on one subpath, the start then the end; what can't be done stays as it is. +fn extend(sp: &SubPath, p: &Value) -> SubPath { + let total = sp.anchor_arc_positions().last().copied().unwrap_or(0.0); + let by = |length, percent| { + num(p, length, 0.0).clamp(-MAX_EXTEND, MAX_EXTEND) + num(p, percent, 0.0).clamp(-MAX_EXTEND_PERCENT, MAX_EXTEND_PERCENT) / 100.0 * total + }; + let shape = |key| if text(p, key, "straight") == "arc" { ExtendMode::Arc } else { ExtendMode::Straight }; + let ends = [(true, by("startLength", "startPercent"), shape("startShape")), (false, by("endLength", "endPercent"), shape("endShape"))]; + let mut out = sp.clone(); + for (at_start, by, shape) in ends { + if by != 0.0 + && let Some(changed) = tools::extend_open(&out, at_start, by, shape) + { + out = changed; + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/effects/src/addons/path/tests.rs b/crates/effects/src/addons/path/tests.rs new file mode 100644 index 0000000000..ef99706cc9 --- /dev/null +++ b/crates/effects/src/addons/path/tests.rs @@ -0,0 +1,278 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::Effect; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath}; + +use super::*; +use crate::{apply_geometry, effect_info, is_geometry, is_length, is_raster, length_range}; + +fn pt(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +fn line(pts: &[(f64, f64)], closed: bool) -> PathData { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| pt(x, y)).collect::>(), closed)) +} + +fn square() -> PathData { + line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true) +} + +/// A curve: a smooth anchor between two ends. +fn curve() -> PathData { + let mid = Anchor::smooth(pt(50.0, -30.0), pt(70.0, -30.0)); + PathData::single(SubPath::new( + vec![ + Anchor { h_out: pt(10.0, -20.0), ..Anchor::corner(pt(0.0, 0.0)) }, + mid, + Anchor { h_in: pt(90.0, -20.0), ..Anchor::corner(pt(100.0, 0.0)) }, + ], + false, + )) +} + +fn run(id: &str, params: Value, path: &PathData) -> PathData { + let e = Effect { id: id.into(), params, visible: true }; + apply_geometry(&[e], path, path.bounds().unwrap_or(Rect::ZERO)) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-3 +} + +const ALL: [&str; 9] = [DASHES, ADD_ANCHORS, EXTEND, CLOSE, SMOOTH, RETRACT, REVERSE, SIMPLIFY, SPLIT]; + +#[test] +fn the_effects_are_geometry_effects_of_the_path_effects_menu() { + for id in ALL { + let info = effect_info(id).unwrap(); + assert!(is_geometry(id) && !is_raster(id), "{id}"); + assert_eq!(info.menu, ["Effect", "Path Effects"], "{id}"); + assert!(id.starts_with(PREFIX)); + } + assert!(is_length(DASHES, "gap5", false) && is_length(EXTEND, "endLength", false) && !is_length(EXTEND, "endPercent", false)); + assert_eq!(length_range(DASHES, "offset"), Some(-10_000.0..=10_000.0)); +} + +#[test] +fn dashes_become_open_subpaths_along_the_path() { + let out = run(DASHES, json!({"dash1": 10, "gap1": 5}), &line(&[(0.0, 0.0), (100.0, 0.0)], false)); + assert_eq!(out.subpaths.len(), 7, "periods of 15 on 100"); + assert!(out.subpaths.iter().all(|s| !s.closed)); + assert!(near(out.subpaths[1].anchors[0].p.x, 15.0) && near(out.subpaths[1].anchors[1].p.x, 25.0)); + // Two pairs, and a pair of zeros between them left out. + let out = run(DASHES, json!({"dash1": 10, "gap1": 5, "dash3": 20, "gap3": 5}), &line(&[(0.0, 0.0), (100.0, 0.0)], false)); + assert!(near(out.subpaths[1].anchors[0].p.x, 15.0) && near(out.subpaths[1].anchors[1].p.x, 35.0)); + assert!(near(out.subpaths[2].anchors[0].p.x, 40.0)); + // The offset starts part way into the pattern. + let out = run(DASHES, json!({"dash1": 10, "gap1": 5, "offset": 5}), &line(&[(0.0, 0.0), (100.0, 0.0)], false)); + assert!(near(out.subpaths[0].anchors[1].p.x, 5.0)); +} + +#[test] +fn aligned_dashes_centre_on_corners_and_ends() { + let open = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false); + let out = run(DASHES, json!({"dash1": 10, "gap1": 10, "alignCorners": true}), &open); + let on = |p: Point| out.subpaths.iter().any(|s| (0..s.segment_count()).any(|i| s.anchors[i].p == p || s.anchors[i + 1].p == p)); + assert!(on(pt(0.0, 0.0)) && on(pt(100.0, 100.0)), "a dash on each end"); + let corner = out.subpaths.iter().find(|s| s.anchors.iter().any(|a| a.p == pt(100.0, 0.0))).expect("a dash over the corner"); + assert!(near(corner.anchors[0].p.distance(pt(100.0, 0.0)), corner.anchors[2].p.distance(pt(100.0, 0.0))), "centred: {corner:?}"); +} + +#[test] +fn zero_dashes_are_points_and_patterns_of_nothing_leave_the_path() { + let path = line(&[(0.0, 0.0), (100.0, 0.0)], false); + let dots = run(DASHES, json!({"dash1": 0, "gap1": 25}), &path); + assert_eq!(dots.subpaths.len(), 5); + assert!(dots.subpaths.iter().all(|s| s.anchors.len() == 2 && s.anchors[0].p == s.anchors[1].p)); + for params in [ + json!({"dash1": 0, "gap1": 0}), + json!({"dash1": -5, "gap1": -5}), + json!({"dash1": 0.0001, "gap1": 0.0001}), + json!({"dash1": "x", "gap1": null}), + ] { + assert_eq!(run(DASHES, params.clone(), &path), path, "{params}"); + } +} + +#[test] +fn add_anchors_spaces_them_and_keeps_to_the_caps() { + let square = square(); + assert_eq!(run(ADD_ANCHORS, json!({}), &square).anchor_count(), 8, "one on each segment"); + assert_eq!(run(ADD_ANCHORS, json!({"count": 3}), &square).anchor_count(), 16); + assert_eq!(run(ADD_ANCHORS, json!({"count": 3, "maxCount": 2}), &square).anchor_count(), 12); + let out = run(ADD_ANCHORS, json!({"spacing": "distance", "distance": 30}), &square); + assert_eq!(out.anchor_count(), 16, "at 30, 60 and 90 on each side"); + assert!(near(out.subpaths[0].anchors[2].p.x, 60.0)); + assert_eq!(run(ADD_ANCHORS, json!({"spacing": "distance", "distance": 25}), &square).anchor_count(), 16, "none on the segment's end"); + assert_eq!(run(ADD_ANCHORS, json!({"spacing": "distance", "distance": 1e-9, "maxCount": 2}), &square).anchor_count(), 12); + // Only the segments asked for. + let mixed = PathData::new(vec![curve().subpaths[0].clone(), square.subpaths[0].clone()]); + assert_eq!(run(ADD_ANCHORS, json!({"target": "curved"}), &mixed).anchor_count(), 7 + 2); + assert_eq!(run(ADD_ANCHORS, json!({"target": "straight"}), &mixed).anchor_count(), 7 + 4); + // The shape stays. + let out = run(ADD_ANCHORS, json!({"count": 4}), &curve()); + assert_eq!(out.anchor_count(), 3 + 8); + assert!(near(out.length(), curve().length())); + assert_eq!(out.bounds().map(|b| (b.y0 * 100.0).round()), curve().bounds().map(|b| (b.y0 * 100.0).round())); +} + +#[test] +fn add_anchors_past_the_budget_leaves_the_path() { + let path = square(); + let most = json!({"count": 1000, "maxCount": 1000}); + assert_eq!(super::apply(ADD_ANCHORS, &most, &path, 4003), path); + assert_eq!(super::apply(ADD_ANCHORS, &most, &path, 4004).anchor_count(), 4004); + // Many segments, each with the most anchors: refused before they are built. + let long = line(&(0..4000).map(|i| (i as f64, 0.0)).collect::>(), false); + assert_eq!(run(ADD_ANCHORS, json!({"count": 1000, "maxCount": 1000}), &long).anchor_count(), 4000, "4 million would pass the budget"); +} + +#[test] +fn extend_lengthens_and_shortens_each_end() { + let path = line(&[(0.0, 0.0), (100.0, 0.0)], false); + let out = run(EXTEND, json!({"startLength": 20, "endLength": 10}), &path); + let xs: Vec = out.subpaths[0].anchors.iter().map(|a| a.p.x).collect(); + assert_eq!(xs, [-20.0, 0.0, 100.0, 110.0]); + // Percent of the path's length, adding to the length; negative shortens. + let out = run(EXTEND, json!({"startLength": 0, "endLength": 5, "endPercent": 10}), &path); + assert!(out.subpaths[0].anchors.last().is_some_and(|a| near(a.p.x, 115.0))); + let out = run(EXTEND, json!({"startLength": -10, "endLength": 0, "endPercent": -50}), &path); + let xs: Vec = out.subpaths[0].anchors.iter().map(|a| a.p.x).collect(); + assert!(near(xs[0], 10.0) && near(xs[1], 50.0), "{xs:?}"); + // An arc carries on round the end's curve. + let arc = run(EXTEND, json!({"startLength": 0, "endLength": 40, "endShape": "arc"}), &curve()); + let straight = run(EXTEND, json!({"startLength": 0, "endLength": 40}), &curve()); + assert!(arc.anchor_count() >= straight.anchor_count()); + assert!((arc.length() - straight.length()).abs() < 0.1); + assert_ne!(arc.subpaths[0].anchors.last().map(|a| a.p), straight.subpaths[0].anchors.last().map(|a| a.p)); +} + +#[test] +fn extend_leaves_what_it_cannot_change() { + let closed = square(); + assert_eq!(run(EXTEND, json!({"endLength": 50}), &closed), closed); + let path = line(&[(0.0, 0.0), (100.0, 0.0)], false); + assert_eq!(run(EXTEND, json!({"startLength": 0, "endLength": -500}), &path), path, "nothing would be left"); + assert_eq!(run(EXTEND, json!({"startLength": 0, "endLength": 0, "endPercent": -100}), &path), path); + let one = PathData::single(SubPath::polyline(&[pt(1.0, 1.0)], false)); + assert_eq!(run(EXTEND, json!({}), &one), one); +} + +#[test] +fn close_joins_open_subpaths_straight_or_smooth() { + let open = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false); + let out = run(CLOSE, json!({}), &open); + assert!(out.subpaths[0].closed && out.subpaths[0].segment_is_line(2)); + let out = run(CLOSE, json!({"mode": "smooth"}), &open); + assert!(out.subpaths[0].closed && !out.subpaths[0].segment_is_line(2)); + assert_eq!(run(CLOSE, json!({}), &square()), square()); + let one = PathData::single(SubPath::polyline(&[pt(1.0, 1.0)], false)); + assert_eq!(run(CLOSE, json!({}), &one), one); +} + +#[test] +fn smooth_makes_a_square_round_and_clamps_its_ratio() { + let out = run(SMOOTH, json!({}), &square()); + assert!(out.subpaths[0].anchors.iter().all(|a| near(a.h_out.distance(a.p), 39.05) && a.has_in())); + let at = |ratio: f64| run(SMOOTH, json!({ "ratio": ratio }), &square()).subpaths[0].anchors[0]; + assert!(near(at(9.0).h_out.distance(pt(0.0, 0.0)), 50.0)); + assert!(near(at(-9.0).h_out.distance(pt(0.0, 0.0)), 1.0)); +} + +#[test] +fn retract_takes_all_handles_or_the_short_ones() { + let out = run(RETRACT, json!({}), &curve()); + assert!(out.subpaths[0].anchors.iter().all(|a| !a.has_in() && !a.has_out())); + // The ends' handles are about 22 pt long and the middle anchor's 20. + let out = run(RETRACT, json!({"handles": "shorter", "length": 21}), &curve()); + let a = &out.subpaths[0].anchors; + assert!(!a[1].has_in() && !a[1].has_out() && a[0].has_out() && a[2].has_in()); + assert_eq!(run(RETRACT, json!({"handles": "shorter", "length": 1}), &curve()), curve()); +} + +#[test] +fn reverse_runs_the_other_way_and_twice_is_as_it_was() { + let out = run(REVERSE, json!({}), &curve()); + assert_eq!(out.subpaths[0].anchors[0].p, pt(100.0, 0.0)); + assert_eq!(run(REVERSE, json!({}), &out), curve()); +} + +#[test] +fn simplify_takes_anchors_within_the_tolerance_and_stops_at_its_cap() { + let pts: Vec<(f64, f64)> = (0..=40).map(|i| (i as f64, (i as f64 / 40.0 * std::f64::consts::PI).sin() * 3.0)).collect(); + let path = line(&pts, false); + let out = run(SIMPLIFY, json!({"tolerance": 200}), &path); + assert!(out.anchor_count() < 20, "{}", out.anchor_count()); + assert_eq!(run(SIMPLIFY, json!({"tolerance": 0}), &path), path); + // Corners stay unless told otherwise. + let corner = line(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)], false); + assert_eq!(run(SIMPLIFY, json!({"tolerance": 200}), &corner), corner); + assert_eq!(run(SIMPLIFY, json!({"tolerance": 200, "protectCorners": false}), &corner).anchor_count(), 2); + let long = line(&(0..=MAX_SIMPLIFY_ANCHORS).map(|i| (i as f64, 0.0)).collect::>(), false); + assert_eq!(run(SIMPLIFY, json!({}), &long).anchor_count(), long.anchor_count()); +} + +#[test] +fn split_cuts_at_the_anchors_asked_for() { + let mixed = PathData::single(SubPath::new( + vec![ + Anchor::corner(pt(0.0, 0.0)), + Anchor::smooth(pt(50.0, 0.0), pt(60.0, 0.0)), + Anchor::corner(pt(100.0, 0.0)), + Anchor::corner(pt(100.0, 50.0)), + ], + false, + )); + assert_eq!(run(SPLIT, json!({}), &mixed).subpaths.len(), 3); + assert_eq!(run(SPLIT, json!({"anchors": "smooth"}), &mixed).subpaths.len(), 2); + assert_eq!(run(SPLIT, json!({"anchors": "corner"}), &mixed).subpaths.len(), 2); + let out = run(SPLIT, json!({}), &square()); + assert_eq!(out.subpaths.len(), 4); + assert!(out.subpaths.iter().all(|s| !s.closed && s.anchors.len() == 2)); + assert!(near(out.length(), 400.0)); + assert_eq!(run(SPLIT, json!({"anchors": "smooth"}), &square()), square(), "no smooth anchors"); +} + +/// Whatever a file holds: every effect takes wrong types, huge numbers and paths of nothing, of one +/// anchor or past measuring, and keeps to the budget. +#[test] +fn junk_params_and_paths_are_harmless() { + let junk = [ + json!({}), + json!(null), + json!([1, 2]), + json!("x"), + json!({"dash1": 1e308, "gap1": 1e308, "dash2": -1e308, "gap2": "x", "offset": 1e308, "alignCorners": "yes"}), + json!({"dash1": 1e-300, "gap1": 1e-300, "offset": -1e308, "alignCorners": true}), + json!({"target": 3, "spacing": ["distance"], "count": 1e308, "distance": 1e-308, "maxCount": -1e308}), + json!({"spacing": "distance", "distance": -1e308, "maxCount": 1e308}), + json!({"startLength": 1e308, "startPercent": 1e308, "startShape": 7, "endLength": -1e308, "endPercent": -1e308, "endShape": "arc"}), + json!({"mode": {}, "ratio": 1e308, "handles": "shorter", "length": 1e308, "tolerance": 1e308, "protectCorners": "no", "anchors": 9}), + json!({"ratio": -1e308, "length": -1e308, "tolerance": -1e308, "anchors": "none"}), + ]; + let far = line(&[(1e308, -1e308), (-1e308, 1e308), (1e300, 0.0)], false); + let nan = line(&[(f64::NAN, 0.0), (f64::INFINITY, 1.0)], false); + let tiny = line(&[(0.0, 0.0), (1e-300, 0.0), (1e-300, 1e-300)], true); + let same = line(&[(5.0, 5.0), (5.0, 5.0), (5.0, 5.0)], true); + let empty = PathData::single(SubPath::default()); + let one = PathData::single(SubPath::polyline(&[pt(1.0, 1.0)], true)); + let paths = [square(), curve(), far.clone(), nan.clone(), tiny, same, empty, one, PathData::default()]; + for id in ALL { + for params in &junk { + for path in &paths { + let out = super::apply(id, &crate::merged_params(id, params), path, 100_000); + assert!(out.anchor_count() <= 100_000.max(path.anchor_count()) + 8 * path.subpaths.len(), "{id} {params}"); + } + } + // Compared as text: NaN never equals itself. + assert_eq!(format!("{:?}", super::apply(id, &json!({}), &nan, 100)), format!("{nan:?}"), "{id}"); + assert_eq!(super::apply(id, &json!({}), &far, 100), far, "{id}"); + } +} + +/// The dash generator's limit holds: a pattern too fine for the path leaves it solid. +#[test] +fn too_many_dashes_leave_the_path() { + let long = line(&[(0.0, 0.0), (1e9, 0.0)], false); + assert_eq!(run(DASHES, json!({"dash1": 1, "gap1": 1}), &long), long); +} diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index faa7a5a7c5..a656f11e85 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -14,9 +14,10 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint, keep_model}; -use vectorcraft_doc::recolor::{ColorVisitor, Reach, map_paint, recolor_node}; +use vectorcraft_doc::recolor::{ColorVisitor, Reach, map_links, recolor_node}; use vectorcraft_doc::{Document, Effect, Node, NodeKind}; +use crate::addons::duotone::{Duotone, SwatchKinds}; use crate::merged_params; use crate::raster::color_param; use crate::util::{flag, num, text}; @@ -27,7 +28,7 @@ pub const ADJUSTMENTS: [&str; 6] = /// Is `id` a colour adjustment effect? pub fn is_adjustment(id: &str) -> bool { - ADJUSTMENTS.contains(&id) + ADJUSTMENTS.contains(&id) || crate::addons::color::is_color_effect(id) } fn visible_adjustment(e: &Effect) -> bool { @@ -72,7 +73,7 @@ pub fn is_channel(s: &str) -> bool { } /// Entries of a sampled tone curve. -const LUT: usize = 256; +pub(crate) const LUT: usize = 256; /// One adjustment, its parameters normalised. #[derive(Clone, Debug, PartialEq)] @@ -88,6 +89,18 @@ enum Adjust { ShiftToColor { target: [f32; 3], amount: f32, preserve: bool }, /// Warm/cool and magenta/green shifts, -1..1. TemperatureTint { temperature: f32, tint: f32 }, + /// One of the Color Effects add-on's. + Addon(crate::addons::color::Adjust), +} + +impl Adjust { + /// Duotone, which maps a colour with its swatch link ([`ColorMap::apply_link`]). + fn duotone(&self) -> Option<&Duotone> { + match self { + Adjust::Addon(crate::addons::color::Adjust::Duotone(d)) => Some(d), + _ => None, + } + } } /// The colour adjustments of an effect list, composed in order. @@ -102,17 +115,44 @@ impl ColorMap { /// Adjust display (sRGB) components 0..1. pub fn apply_rgb(&self, rgb: [f32; 3]) -> [f32; 3] { - self.0.iter().fold(rgb, |c, a| a.apply(c).map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 })) + apply_rgb(&self.0, rgb) } /// Adjust a colour, keeping its colour model (unchanged when the adjustments leave it as is). + /// Duotone gives its inks' colour instead ([`Duotone`]). pub fn apply(&self, c: Color) -> Color { - let rgb = c.to_rgb(); - let out = self.apply_rgb(rgb); - if out.iter().zip(rgb).all(|(a, b)| (a - b).abs() < 1e-6) { - return c; + let (mut c, mut link, mut tint) = (c, None, 1.0); + self.apply_link(&mut c, &mut link, &mut tint, &|_| None); + c + } + + /// Adjust a colour with its swatch link and tint (`link`, `tint`), as a paint holds them; + /// true when it changed. A colour that changes loses its link, except that Duotone with one + /// tone of a swatch the document has (`swatches`, [`SwatchKinds`]) links it to that swatch at + /// the tone's tint. The adjustments between Duotones work in display RGB, each run keeping + /// the colour's model. + pub fn apply_link(&self, c: &mut Color, link: &mut Option, tint: &mut f32, swatches: &SwatchKinds) -> bool { + let mut changed = false; + let mut rest: &[Adjust] = &self.0; + while !rest.is_empty() { + let (run, after) = rest.split_at(rest.iter().position(|a| a.duotone().is_some()).unwrap_or(rest.len())); + if !run.is_empty() { + let rgb = c.to_rgb(); + let out = apply_rgb(run, rgb); + if !out.iter().zip(rgb).all(|(a, b)| (a - b).abs() < 1e-6) { + *c = keep_model(*c, Color::rgb(out[0], out[1], out[2])); + *link = None; + *tint = 1.0; + changed = true; + } + } + let Some((duotone, tail)) = after.split_first() else { break }; + if let Some(d) = duotone.duotone() { + changed |= d.map_link(c, link, tint, swatches); + } + rest = tail; } - keep_model(c, Color::rgb(out[0], out[1], out[2])) + changed } /// Adjust an 8-bit sRGB pixel. @@ -122,6 +162,11 @@ impl ColorMap { } } +/// Display (sRGB) components 0..1 through `adjustments`, in order. +fn apply_rgb(adjustments: &[Adjust], rgb: [f32; 3]) -> [f32; 3] { + adjustments.iter().fold(rgb, |c, a| a.apply(c).map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 })) +} + /// The visible colour adjustments of `effects` as one map, `None` when there are none. pub fn color_map(effects: &[Effect]) -> Option { let v: Vec = @@ -175,7 +220,7 @@ impl Adjust { preserve: flag(p, "preserveLightness", true), }, "adjust.temperatureTint" => Adjust::TemperatureTint { temperature: amount(p, "temperature"), tint: amount(p, "tint") }, - _ => return None, + _ => Adjust::Addon(crate::addons::color::Adjust::parse(id, p)?), }) } @@ -225,17 +270,18 @@ impl Adjust { let (t, m) = (temperature * 0.3, tint * 0.3); [r * (1.0 + t), g * (1.0 - m), b * (1.0 - t)] } + Adjust::Addon(a) => a.apply([r, g, b]), } } } /// `f` sampled at [`LUT`] inputs 0..1. -fn sample(f: impl Fn(f32) -> f32) -> Arc<[f32]> { +pub(crate) fn sample(f: impl Fn(f32) -> f32) -> Arc<[f32]> { (0..LUT).map(|i| f(i as f32 / (LUT - 1) as f32).clamp(0.0, 1.0)).collect() } /// The tone curve `lut` at `v` (linear between samples). -fn lookup(lut: &[f32], v: f32) -> f32 { +pub(crate) fn lookup(lut: &[f32], v: f32) -> f32 { let x = v.clamp(0.0, 1.0) * (LUT - 1) as f32; let i = (x.floor() as usize).min(LUT - 2); let (a, b) = (lut.get(i).copied().unwrap_or(v), lut.get(i + 1).copied().unwrap_or(v)); @@ -245,6 +291,12 @@ fn lookup(lut: &[f32], v: f32) -> f32 { /// Curves' points (0..1 each, sorted by input, one per input) from its `points` parameter: /// `"x,y x,y …"` or `[[x, y], …]` in 0..255. Missing or unreadable points give the identity line. pub fn curve_points(v: Option<&Value>) -> Vec<(f32, f32)> { + // At most a point per level is meaningful. + curve_points_on(v, 255.0, 256) +} + +/// [`curve_points`] on a scale of 0..`max`, reading at most `cap` points. +pub fn curve_points_on(v: Option<&Value>, max: f64, cap: usize) -> Vec<(f32, f32)> { let mut pts: Vec<(f64, f64)> = match v { Some(Value::String(s)) => s .split(|c: char| c.is_whitespace() || c == ';') @@ -257,10 +309,9 @@ pub fn curve_points(v: Option<&Value>) -> Vec<(f32, f32)> { _ => vec![], }; pts.retain(|(x, y)| x.is_finite() && y.is_finite()); - // At most a point per level is meaningful. - pts.truncate(256); - let mut pts: Vec<(f32, f32)> = - pts.into_iter().map(|(x, y)| ((x.clamp(0.0, 255.0) / 255.0) as f32, (y.clamp(0.0, 255.0) / 255.0) as f32)).collect(); + pts.truncate(cap); + let unit = |v: f64| (v.clamp(0.0, max) / max) as f32; + let mut pts: Vec<(f32, f32)> = pts.into_iter().map(|(x, y)| (unit(x), unit(y))).collect(); pts.sort_by(|a, b| a.0.total_cmp(&b.0)); pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); if pts.len() < 2 { @@ -354,15 +405,22 @@ fn from_hsl([h, s, l]: [f32; 3]) -> [f32; 3] { /// Gives the key of an embedded image recoloured by a map (`None`: leave it as it is). pub type ImageHook<'a> = dyn FnMut(&str, &ColorMap) -> Option + 'a; -/// The live visitor: every colour through `map`, embedded images through the hook. +/// The live visitor: every colour through `map` (paints with their swatch links, the document's +/// swatches being `swatches`), embedded images through the hook. struct Live<'a, 'b> { map: &'a ColorMap, + swatches: &'a SwatchKinds<'b>, images: &'a mut ImageHook<'b>, } +/// `p`'s colours through `map` with their swatch links ([`ColorMap::apply_link`]). +fn map_paint(p: &mut Paint, map: &ColorMap, swatches: &SwatchKinds) -> bool { + map_links(p, &|c, link, tint| map.apply_link(c, link, tint, swatches)) +} + impl ColorVisitor for Live<'_, '_> { fn paint(&mut self, p: &mut Paint) -> bool { - map_paint(p, &|c| self.map.apply(c)) + map_paint(p, self.map, self.swatches) } fn color(&mut self, c: Color) -> Color { self.map.apply(c) @@ -375,12 +433,13 @@ impl ColorVisitor for Live<'_, '_> { /// `n` with the colour adjustments in it applied, `None` when it has none: its members' first, /// then those of its fills and strokes on their paints, then its own followed by `outer` (the /// adjustments of an object `n` is the art of) on everything it paints. The adjustment effects -/// are gone from the result; embedded images take the keys `images` gives. -pub fn adjust(n: &Node, outer: Option<&ColorMap>, images: &mut ImageHook<'_>) -> Option { +/// are gone from the result; embedded images take the keys `images` gives. `swatches` tells the +/// document's global and spot swatches apart ([`crate::addons::duotone::swatch_kind`]). +pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images: &mut ImageHook<'_>) -> Option { let mut m: Option = None; if let Some(ch) = n.children() { for (i, c) in ch.iter().enumerate() { - if let Some(new) = adjust(c, None, images) + if let Some(new) = adjust(c, None, swatches, images) && let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i)) { *slot = Arc::new(new); @@ -391,7 +450,7 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, images: &mut ImageHook<'_>) -> if let Some(map) = color_map(item.effects()) && let Some(it) = m.get_or_insert_with(|| n.clone()).appearance.items.get_mut(i) { - map_paint(it.paint_mut(), &|c| map.apply(c)); + map_paint(it.paint_mut(), &map, swatches); it.effects_mut().retain(|e| !is_adjustment(&e.id)); } } @@ -403,7 +462,7 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, images: &mut ImageHook<'_>) -> if let Some(map) = map { let mm = m.get_or_insert_with(|| n.clone()); mm.appearance.effects.retain(|e| !is_adjustment(&e.id)); - recolor_node(mm, Reach::ALL, &mut Live { map: &map, images }); + recolor_node(mm, Reach::ALL, &mut Live { map: &map, swatches, images }); } m } @@ -414,19 +473,20 @@ pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option { let art; let src = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => { - let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()); - art = crate::reshape::as_art(Some(d), n, symbol.as_deref())?; + let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)); + art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?; &art } _ => n, }; + let kinds = crate::addons::duotone::swatch_kinds(d); let mut hook = |key: &str, map: &ColorMap| -> Option { let blob = d.images.get(key)?.map_rgb(|rgb| map.apply_rgb8(rgb))?; let k = blob.content_key(); d.images.entry(k.clone()).or_insert(blob); Some(k) }; - adjust(src, None, &mut hook) + adjust(src, None, &|name| kinds.get(name).copied(), &mut hook) } #[cfg(test)] @@ -489,17 +549,17 @@ mod tests { let mut g = Node::group(NodeId(1), vec![leaf(2), leaf(3)]); g.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true }); assert!(has_adjustment(&g)); - let out = adjust(&g, None, &mut |_, _| None).unwrap(); + let out = adjust(&g, None, &|_| None, &mut |_, _| None).unwrap(); assert!(out.appearance.effects.is_empty()); for c in out.children().unwrap() { assert_eq!(c.appearance.fill_paint().color().unwrap().to_hex(), "#00ff00"); } // A hidden effect does nothing; a stroke's own effect recolours just that stroke. g.appearance.effects[0].visible = false; - assert!(!has_adjustment(&g) && adjust(&g, None, &mut |_, _| None).is_none()); + assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None).is_none()); let mut p = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); p.appearance.items[1].effects_mut().push(Effect { id: "adjust.levels".into(), params: json!({"outputBlack": 255}), visible: true }); - let out = adjust(&p, None, &mut |_, _| None).unwrap(); + let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap(); assert_eq!(out.appearance.items[1].paint().color().unwrap().to_hex(), "#ffffff"); assert_eq!(out.appearance.items[0].paint(), p.appearance.items[0].paint()); assert!(out.appearance.items[1].effects().is_empty()); @@ -514,7 +574,7 @@ mod tests { let fill = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0); let mut p = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill); p.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true }); - let out = adjust(&p, None, &mut |_, _| None).unwrap(); + let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap(); let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient fill") }; // The points are what a freeform gradient draws from, not its stops. let hexes: Vec = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect(); diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index c92947ac3c..ee8aba6c26 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -52,6 +52,7 @@ pub fn needs_bake(n: &Node) -> bool { || crate::has_solid(n) || has_adjustment(n) || has_crop_marks(n) + || crate::addons::halftone::has_halftone(n) || has_pathfinder(n) || has_own_paint(n) || has_geometry(&n.appearance.effects) @@ -104,6 +105,10 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { if let Some(m) = crop_marks_art(n) { return Some(bake_pieces(d, m)); } + // Vector Halftone: the object as its dots. + if let Some(m) = crate::addons::halftone::halftone_art(d, n) { + return Some(bake_pieces(d, m)); + } if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); @@ -117,10 +122,12 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { return Some(bake_pieces(d, m)); } let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), + NodeKind::SymbolInstance { symbol, .. } => { + d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)) + } _ => None, }; - let m = reshape(Some(d), n, symbol.as_deref())?; + let m = reshape(Some(d), n, symbol.as_ref())?; return Some(bake_node(d, &m).unwrap_or(m)); } // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index e000b930f4..bab9ee6ed1 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -42,6 +42,20 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool { catalog_index().get(id).is_some_and(|info| info.lengths.keys(relative).any(|k| k == key)) } +/// The range in points that distance parameter `key` of effect `id` is kept within, as its +/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none. +pub fn length_range(id: &str, key: &str) -> Option> { + let doc = catalog_index().get(id)?.params; + let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); + let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { + let rest = doc.get(at + key.len()..)?; + rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt ")) + })?; + let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?; + let (lo, hi) = (lo.parse::().ok()?, hi.trim_end_matches(',').parse::().ok()?); + (lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi) +} + /// The distance parameters of effect `id` (none for unknown effects). fn lengths_of(id: &str) -> Lengths { let always = |always| Lengths { always, absolute: &[] }; @@ -777,6 +791,9 @@ pub fn effect_catalog() -> Vec { v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({}))); } } + v.extend(crate::addons::color::catalog()); + v.extend(crate::addons::halftone::catalog()); + v.extend(crate::addons::path::catalog()); v.push(g(TRAP, "Trap…", PATHFINDER, trap::EFFECT_PARAMS_DOC, trap::effect_defaults())); v.push(g( CROP_MARKS, diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index a4cb2e1d87..f6f007b5c3 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -114,16 +114,67 @@ pub fn apply_geometry_with(effects: &[Effect], path: &PathData, bounds: Rect, ct apply_geometry_within(effects, path, bounds, ctx, Budget::EFFECTS) } +/// Does effect `e` safely commute with pure translation when it is terminal? +/// Only positive offsets with round joins commute exactly with pure translations for non-zero fills (#4145). +fn is_terminal_offset_eligible(e: &Effect) -> bool { + if e.id != "path.offsetPath" { + return false; + } + let p = merged_params(&e.id, &e.params); + util::join(&p, "joins") == vectorcraft_pathops::Join::Round && util::num(&p, "offset", 10.0) >= 0.0 +} + +/// Optimize a list of visible geometry effects: move pure-translation Transform effects with +/// copies after a terminal Offset Path effect when the effective style is safe (NonZero fill and +/// no stroke), so that the offset path is evaluated once on the base path rather than on dozens +/// of overlapping copies, avoiding combinatorial explosions in the planar sweep (#4145). +pub(crate) fn optimize_geometry_effects<'a>(effects: &[&'a Effect], style_safe: bool) -> Vec<&'a Effect> { + let mut out: Vec<&'a Effect> = effects.to_vec(); + if !style_safe || out.len() < 2 { + return out; + } + let mut changed = true; + while changed { + changed = false; + for i in 0..out.len().saturating_sub(1) { + let e1 = out[i]; + if e1.id == "distort.transform" { + let p1 = merged_params(&e1.id, &e1.params); + if let Some((_, copies)) = crate::distort::transform_move(&p1) + && copies > 0 + && is_terminal_offset_eligible(out[i + 1]) + && out.get(i + 2..).is_some_and(|tail| tail.iter().all(|e| e.id == "distort.transform")) + { + out.swap(i, i + 1); + changed = true; + } + } + } + } + out +} + /// [`apply_geometry_with`] whose effects keep to `budget`, raised to what `path` costs where that /// is more. pub(crate) fn apply_geometry_within(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext, budget: Budget) -> PathData { // `budget` raised to what `path` costs, measured once, and only for a path that has geometry // effects. + let has_stroke = match (ctx.item, ctx.appearance) { + (Some(idx), Some(app)) => match app.items.get(idx) { + Some(AppearanceItem::Stroke(s)) => !s.paint.is_none() && s.width > 0.0, + Some(AppearanceItem::Fill(_)) => false, + None => ctx.stroke.is_some_and(|s| !s.paint.is_none() && s.width > 0.0), + }, + _ => ctx.stroke.is_some_and(|s| !s.paint.is_none() && s.width > 0.0), + }; + let style_safe = ctx.rule == FillRule::NonZero && !has_stroke; + let visible_fx: Vec<&Effect> = effects.iter().filter(|e| e.visible && is_geometry(&e.id)).collect(); + let fx = optimize_geometry_effects(&visible_fx, style_safe); let mut limit = None; let mut cur = path.clone(); let mut b = bounds; let mut first = true; - for e in effects.iter().filter(|e| e.visible && is_geometry(&e.id)) { + for e in fx { if !first { b = cur.bounds().unwrap_or(b); } @@ -214,6 +265,7 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" => stylize::convert_to_shape(id, b, p), "stylize.roundCorners" => stylize::round_corners(path, num(p, "radius", 10.0)), "stylize.scribble" => stylize::scribble(path, b, p), + _ if id.starts_with(crate::addons::path::PREFIX) => crate::addons::path::apply(id, p, path, max), _ => match id.strip_prefix("warp.").and_then(WarpStyle::from_id) { Some(style) => warp::warp(path, b, style, p, max), None => path.clone(), diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index ad59278507..cad97ca562 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -7,6 +7,10 @@ //! result keeps the appearance of the object whose paint it takes. Trap ([`crate::trap`]) keeps the //! children and adds its traps above them. //! +//! **Compound shapes** ([`compound_shape_area`]): a compound shape draws as the one area its +//! members' shape modes make, painted by its own appearance as a group's own fills and strokes +//! paint its members. +//! //! **Container appearance** ([`evaluate_container`]): a group's or layer's own fills and strokes //! paint every member's geometry, below or above the members as its contents slot says //! ([`Appearance::contents_at`]); its geometry effects reshape the members as one piece; its raster @@ -16,7 +20,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, ShapeMode, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData, Rect}; use vectorcraft_pathops::{self as po, PathfinderOp}; @@ -45,10 +49,11 @@ fn op_of(id: &str) -> Option { PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2) } -/// Does `n` (a group or layer) carry a visible Pathfinder effect? +/// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape? pub fn has_pathfinder(n: &Node) -> bool { - matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. }) - && n.appearance.effects.iter().any(|e| e.visible && is_pathfinder(&e.id)) + n.is_compound_shape() + || (matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. }) + && n.appearance.effects.iter().any(|e| e.visible && is_pathfinder(&e.id))) } /// Converts objects that aren't paths (e.g. text) to outline art, if possible. The paths and @@ -62,11 +67,15 @@ fn leaves(n: &Node, hook: Option, out: &mut Vec) { } match &n.kind { NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.push(n.clone()), - NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { - for c in children { - leaves(c, hook, out); + // A compound shape takes part as its area, styled like it. + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art(n, hook) { + Some(art) => out.push(art), + None => { + for c in children { + leaves(c, hook, out); + } } - } + }, _ => { // Every path of the outline art, at any depth, takes the object's opacity and blend // mode. @@ -91,6 +100,63 @@ fn geometry(n: &Node) -> Option<(PathData, FillRule)> { } } +/// The operation that combines a compound shape's member in `mode` with the area below it. +fn shape_op(mode: ShapeMode) -> po::BoolOp { + match mode { + ShapeMode::Add => po::BoolOp::Union, + ShapeMode::Subtract => po::BoolOp::Difference, + ShapeMode::Intersect => po::BoolOp::Intersect, + ShapeMode::Exclude => po::BoolOp::Xor, + } +} + +/// The area compound shape `n` draws: each visible member's shape (a group's leaves together, type +/// as its outlines through `hook`, open paths closed) combined with the area of the members below +/// it by the member's shape mode; the backmost member starts the area. `None` when `n` is not a +/// compound shape, or its members are past a live Pathfinder's budget ([`PATHFINDER_MAX_SEGMENTS`], +/// [`PATHFINDER_MAX_OVERLAPS`]). +pub fn compound_shape_area(n: &Node, hook: Option) -> Option { + if !n.is_compound_shape() { + return None; + } + let mut all: Vec = vec![]; + // Each member that has a shape: its operation and how many of the leaves are its. + let mut members: Vec<(po::BoolOp, usize)> = vec![]; + for c in n.children()? { + let before = all.len(); + leaves(c, hook, &mut all); + if all.len() > before { + members.push((shape_op(c.extras().shape_mode), all.len() - before)); + } + } + if !within_budget(&all) { + return None; + } + if all.is_empty() { + return Some(PathData::default()); + } + let parts: Vec<(PathData, FillRule)> = all.iter().map(|l| geometry(l).unwrap_or_default()).collect(); + let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect(); + Some(po::boolean_n(&refs, |inside| { + let (mut start, mut area) = (0, false); + for (k, (op, count)) in members.iter().enumerate() { + let here = inside.get(start..start + count).is_some_and(|flags| flags.contains(&true)); + start += count; + area = if k == 0 { here } else { op.apply(area, here) }; + } + area + })) +} + +/// Compound shape `n` as one path of its area ([`compound_shape_area`]) with its appearance, +/// opacity and blend mode: how it takes part in a Pathfinder operation. +pub fn compound_shape_art(n: &Node, hook: Option) -> Option { + let area = compound_shape_area(n, hook)?; + let mut art = Node::path(n.id, area, Appearance { items: n.appearance.items.clone(), ..Default::default() }); + (art.opacity, art.blend) = (n.opacity, n.blend); + Some(art) +} + /// A result path styled like `src` (its appearance, opacity and blend mode). fn styled(src: &Node, path: PathData, outline: bool) -> Node { let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() }; @@ -196,7 +262,16 @@ pub fn pathfinder_children(group: &Node, hook: Option) -> Option] = group.children()?; - let mut stack: Vec> = source.to_vec(); + let mut stack: Vec> = if group.is_compound_shape() { + // The group's own appearance paints the area ([`evaluate_container`]), so the art has none. + match compound_shape_area(group, hook) { + Some(area) if area.is_empty() => vec![], + Some(area) => vec![Arc::new(Node::path(group.id, area, Appearance::default()))], + None => return Some(source.to_vec()), + } + } else { + source.to_vec() + }; for e in group.appearance.effects.iter().filter(|e| e.visible) { if e.id == crate::trap::TRAP { let mut lv = vec![]; @@ -375,6 +450,13 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } match &n.kind { NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.extend(crate::reshape::leaf_geometry(n)), + NodeKind::Group { .. } if n.is_compound_shape() => { + let hook: &dyn Fn(&Node) -> Option = &crate::outline_text; + match compound_shape_area(n, Some(hook)) { + Some(area) => out.push((area, FillRule::NonZero)), + None => members(doc, n, out), + } + } NodeKind::Text(t) => { let (_, all) = crate::reshape::glyph_outlines(t); if !all.elements().is_empty() { @@ -454,6 +536,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if let Some(ch) = m.children_mut() { *ch = result; } + // The area is art now: drawn again, it is no compound shape of its own. + m.extras_mut().compound_shape = false; } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index c3bf4bfe3f..7c9f649c7a 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -347,3 +347,72 @@ fn pathfinder_on_many_stacked_bars_still_runs() { let out = pathfinder_children(&g, None).unwrap(); assert_eq!(out.len(), 1); } + +/// Two overlapping squares (0–10 and 5–15 by 10 high) as a compound shape, the front one in `mode`. +fn compound_shape(mode: ShapeMode) -> Node { + let mut front = (*sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))).clone(); + front.extras_mut().shape_mode = mode; + let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(front)]); + g.extras_mut().compound_shape = true; + g.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0).into(); + g +} + +/// A compound shape draws the area its members' modes make, one unpainted path that its own +/// appearance paints; evaluated, it is plain art painted with that appearance. +#[test] +fn compound_shapes_draw_the_area_their_shape_modes_make() { + for (mode, want) in [(ShapeMode::Add, 150.0), (ShapeMode::Subtract, 50.0), (ShapeMode::Intersect, 50.0), (ShapeMode::Exclude, 100.0)] { + let g = compound_shape(mode); + assert!(has_pathfinder(&g), "{mode:?}"); + let area_path = compound_shape_area(&g, None).unwrap(); + assert!((po::area(&area_path, FillRule::NonZero).abs() - want).abs() < 0.01, "{mode:?}"); + let out = pathfinder_children(&g, None).unwrap(); + assert_eq!(out.len(), 1, "{mode:?}"); + assert!(out[0].appearance.items.is_empty(), "the group's own appearance paints it"); + let art = evaluate_container(None, &g).unwrap(); + assert!(!art.is_compound_shape(), "evaluated, it is art"); + let painted: Vec<&Arc> = art.children().unwrap().iter().filter(|c| !c.appearance.items.is_empty()).collect(); + assert_eq!(painted.len(), 1); + assert_eq!(painted[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "{mode:?}"); + assert!((area(painted[0]) - want).abs() < 0.01, "{mode:?}"); + } + // The backmost member's mode doesn't change the area. + let mut g = compound_shape(ShapeMode::Add); + if let Some(ch) = g.children_mut() { + let mut back = (*ch[0]).clone(); + back.extras_mut().shape_mode = ShapeMode::Subtract; + ch[0] = Arc::new(back); + } + assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 150.0).abs() < 0.01); + // Hidden members take no part; the mark on a clip group is ignored. + let mut g = compound_shape(ShapeMode::Subtract); + if let Some(ch) = g.children_mut() { + let mut front = (*ch[1]).clone(); + front.visible = false; + ch[1] = Arc::new(front); + } + assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 100.0).abs() < 0.01); + let mut clip = compound_shape(ShapeMode::Add); + clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true }; + assert!(!clip.is_compound_shape() && compound_shape_area(&clip, None).is_none()); +} + +/// A compound shape inside another (and inside an Effect › Pathfinder group) takes part as its area, +/// styled like it. +#[test] +fn nested_compound_shapes_take_part_as_their_area() { + let inner = compound_shape(ShapeMode::Subtract); + let mut cutter = (*sq(3, 2.0, Color::BLACK)).clone(); + cutter.extras_mut().shape_mode = ShapeMode::Intersect; + let mut outer = Node::group(NodeId(20), vec![Arc::new(inner.clone()), Arc::new(cutter)]); + outer.extras_mut().compound_shape = true; + // (0–5 of the inner area) ∩ (2–12) = 2–5 by 10 high. + assert!((po::area(&compound_shape_area(&outer, None).unwrap(), FillRule::NonZero).abs() - 30.0).abs() < 0.01); + let mut effect = Node::group(NodeId(30), vec![Arc::new(inner)]); + effect.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true }); + let out = pathfinder_children(&effect, None).unwrap(); + assert_eq!(out.len(), 1); + assert!((area(&out[0]) - 50.0).abs() < 0.01); + assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape"); +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index e3055da0bc..b15a642c3d 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -34,6 +34,7 @@ //! anchored at the object's centre. #![forbid(unsafe_code)] +pub mod addons; mod adjust; mod bake; mod clip; @@ -69,8 +70,8 @@ pub use adjust::{ pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake}; pub use clip::clip_outline; pub use group::{ - OutlineHook, PATHFINDER_EFFECTS, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_shapes, paints, - pathfinder_children, + OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, + is_pathfinder, member_shapes, paints, pathfinder_children, }; pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, text_outliner}; @@ -94,7 +95,7 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, plugin_effects}; +pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with}; #[cfg(test)] diff --git a/crates/effects/src/live.rs b/crates/effects/src/live.rs index aad8d8edd9..769eae6b53 100644 --- a/crates/effects/src/live.rs +++ b/crates/effects/src/live.rs @@ -24,7 +24,7 @@ fn outline(doc: Option<&Document>, n: &Node) -> Option { match &n.kind { NodeKind::SymbolInstance { symbol, xf } => { let sym = doc?.symbols.iter().find(|s| s.name == *symbol)?; - let mut art = (*sym.art).clone(); + let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n); art.transform(*xf, false); Some(Node::group(n.id, vec![Arc::new(art)])) } diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index d64ac7b780..c8cea82590 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -118,14 +118,16 @@ pub fn is_raster(id: &str) -> bool { || PIXEL_EFFECTS.contains(&id) } -/// Does `id` change geometry? (Crop Marks adds art of its own instead, [`crop_marks_art`]; colour -/// adjustments recolour, [`adjust`].) Plug-in effects do, installed or not (a missing plug-in +/// Does `id` change geometry? (Crop Marks and Vector Halftone add art of their own instead, +/// [`crop_marks_art`] and [`crate::addons::halftone::halftone_art`]; colour adjustments recolour, +/// [`adjust`].) Plug-in effects do, installed or not (a missing plug-in /// leaves the geometry as it is). pub fn is_geometry(id: &str) -> bool { !is_raster(id) && !is_pathfinder(id) && !is_adjustment(id) && id != CROP_MARKS + && id != crate::addons::halftone::HALFTONE && !is_three_d(id) && (catalog_index().contains_key(id) || vectorcraft_plugins::effect::plugin_id(id).is_some()) } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 8cab92a699..0d912b5318 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -431,6 +431,22 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg if fx.is_empty() { return; } + let mut leaves_safe = true; + for_each_leaf(art, &mut |leaf| { + if !leaves_safe { + return; + } + if let Some((_, rule)) = leaf_geometry(leaf) { + let has_stroke = leaf.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); + if rule != FillRule::NonZero || has_stroke { + leaves_safe = false; + } + } + }); + let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0); + let style_safe = leaves_safe && !art_stroke; + let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe); + let fx = opt_fx.as_slice(); let seed = art.id.0; // The placed gradients of type's outlines in `art` (`outline_text`) move and scale with the // pieces, from the outlines' bounds before the effects to their bounds after them. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index a68b7f579d..1165340bc2 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -114,10 +114,34 @@ fn profile(n: &Node) -> Option<(PathData, FillRule)> { NodeKind::Compound { children, rule } => { Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule)) } + // Type extrudes as its glyph outlines and stays type: editing it reshapes the solid (#4715). + NodeKind::Text(_) => { + let mut subpaths = vec![]; + crate::outline_text(n)?.walk(&mut |c| subpaths.extend(c.path_data().into_iter().flat_map(|p| p.subpaths.iter().cloned()))); + (!subpaths.is_empty()).then(|| (PathData::new(subpaths), FillRule::NonZero)) + } _ => None, } } +/// What a 3D effect paints `n` with: its own fills and strokes, else, for type that has none, the +/// fill and stroke of its first painted run (its characters' colours). +fn solid_paints(n: &Node) -> Vec { + let own: Vec = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect(); + if !own.is_empty() || !matches!(n.kind, NodeKind::Text(_)) { + return own; + } + let mut runs = vec![]; + if let Some(outlined) = crate::outline_text(n) { + outlined.walk(&mut |c| { + if runs.is_empty() && c.path_data().is_some() { + runs = c.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect(); + } + }); + } + runs +} + fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result, String> { let view = view_options(p); match id { @@ -320,7 +344,8 @@ pub fn solid_art(n: &Node) -> Option { } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); - let painted: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect(); + let paints = solid_paints(n); + let painted: Vec<&AppearanceItem> = paints.iter().collect(); let mut children = vec![]; let remaining: Vec; if let Some((index, fx)) = solid(&n.appearance.effects) { diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 3996794ace..cff94b0f46 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -438,6 +438,93 @@ fn three_max_detail_roughens_stay_within_the_effect_budget() { assert_ne!(out, apply_geometry(&[rough], &rect, rect.bounds().unwrap()), "more than one Roughen applies"); } +#[test] +fn transform_copies_before_offset_path_evaluates_without_ram_spike() { + let effects = [ + fx("distort.transform", json!({"moveH": -0.66, "moveV": 0.66, "copies": 30})), + fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})), + ]; + let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let start = std::time::Instant::now(); + let out = apply_geometry(&effects, &path, path.bounds().unwrap()); + let elapsed = start.elapsed(); + assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed); + assert_eq!(out.subpaths.len(), 31); +} + +#[test] +fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeId}; + + let id = NodeId(10); + let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 20.0)), Appearance::default())); + let mut art = Node::group(id, (0..5).map(|k| leaf(k as f64 * 30.0)).collect()); + let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10})); + let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); + + let start = std::time::Instant::now(); + crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS); + let elapsed = start.elapsed(); + assert!(elapsed < std::time::Duration::from_secs(2)); + + let children = art.children().unwrap(); + assert_eq!(children.len(), 5); + for c in children { + let (p, _) = crate::reshape::leaf_geometry(c).unwrap(); + // Base rectangle offset once, then copied 10 times -> 11 subpaths + assert_eq!(p.subpaths.len(), 11); + } +} + +#[test] +fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; + + let id = NodeId(11); + // 1. EvenOdd fill rule: preserving order causes Transform copies to union in Offset Path into 1 subpath. + let mut leaf = Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()); + if let NodeKind::Path { rule, .. } = &mut leaf.kind { + *rule = FillRule::EvenOdd; + } + let mut art_evenodd = Node::group(id, vec![Arc::new(leaf)]); + let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 2})); + let offset = fx("path.offsetPath", json!({"offset": 4.0})); + crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS); + let p = art_evenodd.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "EvenOdd does not swap; copies union into 1 outer subpath"); + + // 2. Non-terminal Offset Path: followed by Round Corners, must preserve order. + let leaf_round = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default())); + let mut art_round = Node::group(id, vec![leaf_round]); + let round_corners = fx("stylize.roundCorners", json!({"radius": 2.0})); + crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS); + let p = art_round.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "Non-terminal Offset Path does not swap; copies union into 1 outer subpath"); + + // 3. Non-round join (e.g. miter): preserving order is required as corners differ (#4145). + let leaf_miter = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default())); + let mut art_miter = Node::group(id, vec![leaf_miter]); + let offset_miter = fx("path.offsetPath", json!({"offset": 4.0, "joins": "miter"})); + crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS); + let p = art_miter.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "Miter join does not swap; copies union into 1 outer subpath"); +} + +#[test] +fn consecutive_transforms_before_terminal_offset_path_all_move_after() { + let t1 = fx("distort.transform", json!({"moveH": 1.0, "moveV": 0.0, "copies": 2})); + let t2 = fx("distort.transform", json!({"moveH": 0.0, "moveV": 1.0, "copies": 3})); + let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); + + let opt = crate::geometry::optimize_geometry_effects(&[&t1, &t2, &offset], true); + assert_eq!(opt.len(), 3); + assert_eq!(opt[0].id, "path.offsetPath"); + assert_eq!(opt[1].id, "distort.transform"); + assert_eq!(opt[2].id, "distort.transform"); +} + #[test] fn transform_copies_stop_before_they_overflow() { let out = run("distort.transform", json!({"scaleH": 100000, "scaleV": 100000, "copies": 1000}), &square()); @@ -1104,10 +1191,10 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { let instance = |name: &str| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })); let mut d = Document::new(100.0, 100.0); // A 500 × 500 grid as a symbol's art, directly and inside a group; a symbol holding itself. - d.symbols.push(Symbol { name: "Grid".into(), art: repeat(grid(unit(), 500)) }); - d.symbols.push(Symbol { name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) }); - d.symbols.push(Symbol { name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) }); - d.symbols.push(Symbol { name: "Small".into(), art: repeat(grid(unit(), 3)) }); + d.symbols.push(Symbol { dynamic: false, name: "Grid".into(), art: repeat(grid(unit(), 500)) }); + d.symbols.push(Symbol { dynamic: false, name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) }); + d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) }); + d.symbols.push(Symbol { dynamic: false, name: "Small".into(), art: repeat(grid(unit(), 3)) }); // A 3 × 3 grid of an instance of each: each copy draws 250,000 instances, so one copy fits. for name in ["Grid", "Grouped"] { let outer = Node::new(NodeId(0), NodeKind::Repeat(grid(instance(name), 3))); @@ -1120,3 +1207,17 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { let small = Node::new(NodeId(0), NodeKind::Repeat(RepeatSpec::mirror(vec![instance("Small")], 90.0, 5.0))); assert_eq!(expand_live(Some(&d), &small).len(), 2); } + +#[test] +fn a_distance_parameters_range_comes_from_its_documentation() { + assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + // The effect applies the range's floor to a radius below it. + assert_eq!( + crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})), + crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4})) + ); + // A distance documented without a range, and unknown effects and parameters, have none. + assert_eq!(length_range("path.offsetPath", "offset"), None); + assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None); + assert_eq!(length_range("no.such", "maxRadius"), None); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f495697ceb..9d4ad73995 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -36,9 +36,12 @@ vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } image = { workspace = true } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } flate2 = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). roxmltree = "0.21" +# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). +cfb = "0.15" kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0df04d2c48..31d0ca2cb2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,5 +1,6 @@ //! The command registry. Ids follow Illustrator's menu structure. +mod addons; pub(crate) mod appearance; mod assets; mod attributes; @@ -10,6 +11,7 @@ pub mod clipboard; mod colorcmds; pub mod colormgmt; pub mod colortheme; +mod compoundshape; pub(crate) mod create; mod css; mod cut; @@ -31,6 +33,7 @@ mod fonts; pub(crate) mod freeform; pub mod globaledit; pub(crate) mod gradient; +pub mod gradpresets; pub(crate) mod graph; mod halftone; pub mod help; @@ -81,9 +84,11 @@ mod style; pub mod stylelib; mod swatch; pub mod swatchlib; +pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; mod textedit; +pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; @@ -179,20 +184,26 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) } } -/// A document is open and it is not in isolation mode: Object › Lock's and Object › Hide's items, -/// Unlock All and Show All are off in isolation mode. Pattern editing mode and opacity mask -/// editing isolate their art too, and do not count as isolation mode here while their own layer -/// is the isolated one. An object isolated inside them counts. -pub fn outside_isolation(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let editing_layer = |l| st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == l) || st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == l); - if st.isolation.is_some_and(|l| !editing_layer(l)) { Err("exit isolation mode first".into()) } else { Ok(()) } +/// The isolated group, layer or object in isolation mode. Pattern editing mode, opacity mask +/// editing and symbol editing mode isolate their own layer, which does not count here; an object +/// isolated inside them counts. +pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option { + st.isolation.filter(|l| { + !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) + && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) + && !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) + }) } -/// Objects are selected ([`has_selection`]) and the document is not in isolation mode -/// ([`outside_isolation`]). -pub fn has_selection_outside_isolation(s: &Session) -> std::result::Result<(), String> { - outside_isolation(s)?; - has_selection(s) +/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at +/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. +pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let Some(root) = ordinary_isolation(st) else { return has_selection(s) }; + if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) } +} +/// Whether `id` lies inside the isolated object `root` (the root itself does not). +pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool { + id != root && d.ancestry(id).is_some_and(|a| a.contains(&root)) } pub fn can_undo(s: &Session) -> std::result::Result<(), String> { s.active().filter(|d| !d.history.undo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) @@ -242,6 +253,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(style::specs()); v.extend(swatch::specs()); v.extend(gradient::specs()); + v.extend(gradpresets::specs()); v.extend(opacitymask::specs()); v.extend(layer::specs()); v.extend(layerpanel::specs()); @@ -249,6 +261,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(xform::specs()); v.extend(effectcmd::specs()); v.extend(pathops::specs()); + v.extend(compoundshape::specs()); v.extend(typecmd::specs()); v.extend(menucmds::specs()); v.extend(live::specs()); @@ -320,6 +333,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(perspgrid::specs()); v.extend(shortcutset::specs()); v.extend(importmatches::specs()); + v.extend(addons::specs()); v }) } @@ -378,6 +392,15 @@ pub(crate) fn check_switches(p: &Value, keys: &[&str], cmd: &str) -> Result<()> pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { p.get(key).and_then(Value::as_str) } +/// The string `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other +/// value, such as `5`, is an error: "`{key}` must be a string". +pub(crate) fn text_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(v)) => Ok(Some(v)), + Some(_) => Err(bad(cmd, format!("`{key}` must be a string"))), + } +} pub(crate) fn id_param(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_u64).map(NodeId) } @@ -514,26 +537,30 @@ pub(crate) fn ok() -> Result { } /// Leaves whose appearance a paint command changes: groups and layers expand to their contents, -/// and compound paths own their children's appearance, so a member stands for its compound path -/// (#3692), which is listed once. +/// and compound paths and compound shapes own their members' appearance, so a member stands for +/// its compound path (#3692) or compound shape, which is listed once. pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result> { use vectorcraft_doc::NodeKind; let d = &s.doc()?.doc; - let compound = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let owns = |n: &vectorcraft_doc::Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape(); + let compound = |id: NodeId| d.parent_of(id).filter(|p| d.node(*p).is_some_and(owns)); let mut out = vec![]; for id in ids { let Some(n) = d.node(*id) else { continue }; match &n.kind { - NodeKind::Group { .. } | NodeKind::Layer { .. } => n.walk(&mut |c| { - if !c.is_container() || matches!(c.kind, NodeKind::Compound { .. }) { + NodeKind::Group { .. } | NodeKind::Layer { .. } if !n.is_compound_shape() => n.walk(&mut |c| { + if !c.is_container() || owns(c) { out.push(c.id) } }), _ => out.push(compound(*id).unwrap_or(*id)), } } - let comp: Vec = out.iter().filter(|id| matches!(d.node(**id).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).copied().collect(); - out.retain(|id| !comp.iter().any(|c| d.parent_of(*id) == Some(*c))); + let comp: std::collections::HashSet = out.iter().filter(|id| d.node(**id).is_some_and(owns)).copied().collect(); + if !comp.is_empty() { + // A compound shape's members lie at any depth in it. + out.retain(|id| !d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).any(|a| comp.contains(a)))); + } let mut seen = std::collections::HashSet::new(); out.retain(|id| seen.insert(*id)); Ok(out) @@ -581,6 +608,9 @@ pub use opacitymask::TransparencyInfo; /// Eyedropper Options (`Prefs::eyedropper`). pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, StrokeAttrs}; +/// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs). +pub use compoundshape::selected_member_modes; + /// Pathfinder Options (`Prefs::pathfinder`). pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions}; @@ -593,9 +623,15 @@ pub use flatten::FlattenOptions; /// A built-in or saved flattener preset ([`crate::Prefs::flattener_presets`]). pub use flatten::FlattenerPreset; +/// A saved Gradient panel preset ([`crate::Prefs::gradient_presets`]) and a row of the Presets list. +pub use gradpresets::{GradientPreset, GradientPresetEntry}; + /// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets. pub use buildcmds::{TracePreset, TracePresetChange}; +/// An Image Trace made off the UI thread, and what it traced (#3098). +pub use buildcmds::{TraceRun, Traced}; + /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs new file mode 100644 index 0000000000..21d73cc4f8 --- /dev/null +++ b/crates/engine/src/cmd/addons.rs @@ -0,0 +1,22 @@ +//! VectorCraft's built-in add-ons: extra tools beyond the standard menus, each a module of its own +//! with commands under `addon..*` (see `docs/mcp.md`). + +mod arrange; +mod cleanup; +mod color; +mod document; +mod pathtools; +mod pen; + +use super::CommandSpec; + +/// The commands of every built-in add-on. +pub fn specs() -> Vec { + let mut v = arrange::specs(); + v.extend(cleanup::specs()); + v.extend(color::specs()); + v.extend(document::specs()); + v.extend(pathtools::specs()); + v.extend(pen::specs()); + v +} diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs new file mode 100644 index 0000000000..735d721335 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -0,0 +1,535 @@ +//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects +//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two; +//! Replace with Top Object puts a copy of the topmost selected object in place of each of the +//! others; and Set Size of Each gives every selected object an exact width and height. Places and +//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the +//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random +//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in +//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection +//! (a view command) are the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_doc::{Node, NodeId, OrientedBox}; +use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_render::effects; + +use super::super::edit::selected_roots; +use super::super::menucmds::whole_or; +use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; +use super::super::typecmd::refresh_bounds_of; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The largest gap, width or height (pt) the commands take. +const LIMIT: f64 = 1e6; +/// The smallest width or height (pt) Set Size of Each takes. +const LEAST: f64 = 0.001; +/// The most columns Arrange in Grid takes. +const MAX_COLUMNS: u64 = 10_000; +/// The most objects Group Overlapping Objects and Sort Objects look at. +const MAX_OBJECTS: usize = 20_000; +/// The attributes Sort Objects sorts by and gives (`addon.arrange.sort`). +pub const SORT_KEYS: [&str; 7] = ["width", "height", "area", "x", "y", "opacity", "stacking"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.arrange.grid", + "Arrange in Grid", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{layout?: \"grid\" (rows and columns) | \"row\" (one row) | \"column\" (one column), columns?: 1..10000 (grid; default ⌈√count⌉; never more than the count), gapX?: pt −1000000..1000000 (10), gapY?: pt −1000000..1000000 (gapX), centerOnArtboard?: false (true: the grid is centred on the artboard under the selection's centre, else the first; false: it starts at the selection's top-left)} lay the selected objects (the top-level ones) out in their stacking order from the back, left to right and top to bottom, as one undo step. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, each object is centred in its cell, and everything is measured by visual bounds (strokes and effects as drawn) → {count}", + has_selection, + grid + ), + cmd!( + "addon.arrange.swap", + "Swap Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", + exactly_two, + swap + ), + cmd!( + "addon.arrange.replace", + "Replace with Top Object", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", + has_multi, + replace + ), + cmd!( + "addon.arrange.size", + "Set Size of Each", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", + has_selection, + size + ), + cmd!( + "addon.arrange.groupOverlapping", + "Group Overlapping Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{} group the selected objects (the top-level ones, at most 20000) wherever their visual bounds overlap or touch, chains included (when A overlaps B and B overlaps C, all three go in one group), as one undo step. Only objects in the same layer or group are grouped together, objects that overlap nothing stay as they are, and each new group goes where its frontmost member was in the stacking order; the new groups and the objects left alone stay selected → {groups: [id…], grouped (how many objects went into groups)}", + has_multi, + group_overlapping + ), + cmd!( + "addon.arrange.randomizeOpacity", + "Randomize Opacity", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}", + has_selection, + randomize_opacity + ), + cmd!( + "addon.arrange.sort", + "Sort Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}", + has_multi, + sort + ), + ] +} + +/// Exactly two objects are selected (Swap Objects). +fn exactly_two(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + let n = selected_roots(s).map_err(|e| e.to_string())?.len(); + if n == 2 { Ok(()) } else { Err("select exactly two objects".into()) } +} + +/// Number param `key` (`default` when left out) within `lo..=hi`. +fn number_in(p: &Value, key: &str, default: f64, (lo, hi): (f64, f64), cmd: &str) -> Result { + let v = number_or(p, key, default, cmd)?; + if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// Whole-number param `key` within `lo..=hi`, `None` when left out. +pub(super) fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let n = v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number")))?; + if (lo..=hi).contains(&n) { Ok(Some(n)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// A width or height param of Set Size of Each, `None` when left out. +fn size_param(p: &Value, key: &str, cmd: &str) -> Result> { + p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose() +} + +/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes` +/// and, when given, a width and height. +fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { + let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes }); + if let Some((w, h)) = size { + q["width"] = json!(w); + q["height"] = json!(h); + } + q +} + +/// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects +/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says. +/// When every transform is (within rounding) the identity, nothing changes. +fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { + let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); + if xfs.iter().all(|(_, xf)| still(xf)) { + return Ok(()); + } + let p = json!({ "strokes": strokes }); + let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &ids)?; + s.edit(label, |d, _| { + for (id, xf) in xfs { + if let Some(n) = d.node_mut(*id) { + transform_node(n, *xf, sc, true); + } + } + Ok(()) + }) +} + +/// The box of object `id` as `object.setBounds` measures it. +fn box_of(s: &Session, id: NodeId) -> Result { + s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into())) +} + +fn grid(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.grid"; + let layout = choice(p, C, "layout", &["grid", "row", "column"])?.unwrap_or("grid"); + let columns = whole_in(p, "columns", (1, MAX_COLUMNS), C)?; + let gap_x = number_in(p, "gapX", 10.0, (-LIMIT, LIMIT), C)?; + let gap_y = number_in(p, "gapY", gap_x, (-LIMIT, LIMIT), C)?; + let center = switch_or(p, "centerOnArtboard", false, C)?; + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let items: Vec<(NodeId, Rect)> = roots.iter().filter_map(|id| Some((*id, effects::preview::bounds_of(d, &[*id], true)?))).collect(); + let Some(all) = items.iter().map(|(_, b)| *b).reduce(|a, b| a.union(b)) else { return Ok(json!({ "count": 0 })) }; + let n = items.len(); + let cols = match layout { + "row" => n, + "column" => 1, + _ => columns.map_or_else(|| (n as f64).sqrt().ceil() as usize, |c| usize::try_from(c).unwrap_or(n)), + } + .clamp(1, n); + let mut widths = vec![0.0_f64; cols]; + let mut heights = vec![0.0_f64; n.div_ceil(cols)]; + for (i, (_, b)) in items.iter().enumerate() { + if let Some(w) = widths.get_mut(i % cols) { + *w = w.max(b.width()); + } + if let Some(h) = heights.get_mut(i / cols) { + *h = h.max(b.height()); + } + } + let total = |sizes: &[f64], gap: f64| sizes.iter().sum::() + gap * sizes.len().saturating_sub(1) as f64; + let origin = if center { + let board = d.artboards.get(d.artboard_at(all.center()).unwrap_or(0)).map_or(all, |a| a.rect); + Point::new(board.center().x - total(&widths, gap_x) / 2.0, board.center().y - total(&heights, gap_y) / 2.0) + } else { + Point::new(all.x0, all.y0) + }; + // The middle of each column (row): the sizes and gaps before it, and half its own size. + let middles = |sizes: &[f64], gap: f64, from: f64| -> Vec { + sizes + .iter() + .scan(from, |at, size| { + let mid = *at + size / 2.0; + *at += size + gap; + Some(mid) + }) + .collect() + }; + let (xs, ys) = (middles(&widths, gap_x, origin.x), middles(&heights, gap_y, origin.y)); + let xfs: Vec<(NodeId, Affine)> = items + .iter() + .enumerate() + .filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center())))) + .collect(); + transform_each(s, "Arrange in Grid", false, &xfs)?; + Ok(json!({ "count": n })) +} + +fn swap(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.swap"; + let size = switch_or(p, "size", false, C)?; + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let roots = selected_roots(s)?; + let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; + let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); + let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes); + let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)]; + transform_each(s, "Swap Objects", strokes, &xfs)?; + Ok(json!({})) +} + +fn replace(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.replace"; + let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep"); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let keep = switch_or(p, "keep", false, C)?; + let roots = selected_roots(s)?; + let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else { + return Err(bad(C, "select at least two objects")); + }; + let tb = box_of(s, top)?; + let (tw, th) = (tb.rect.width(), tb.rect.height()); + let mut xfs = Vec::with_capacity(others.len()); + for &id in others { + let Some(b) = s.transform_box(&[id]) else { continue }; + let (w, h) = (b.rect.width(), b.rect.height()); + let size = match fit { + "bounds" => Some((w, h)), + // The smaller of the two scales that fit; a side the copy doesn't have doesn't count. + "proportional" => { + [(w, tw), (h, th)].into_iter().filter(|(_, t)| *t > 1e-9).map(|(v, t)| v / t).reduce(f64::min).map(|k| (tw * k, th * k)) + } + _ => None, + }; + xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?)); + } + let p = json!({ "strokes": strokes }); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &[top])?; + let ids = s.edit("Replace with Top Object", |d, sel| { + let Some(n) = d.node(top).cloned() else { return Ok(vec![]) }; + let mut items = Vec::with_capacity(xfs.len()); + for (id, xf) in &xfs { + let mut c = d.reid(&n); + transform_node(&mut c, *xf, sc, true); + items.push((*id, vec![c])); + } + let out: Vec = items.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect(); + d.insert_beside(items, !keep)?; + refresh_bounds_of(d, &out); + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) +} + +fn size(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.size"; + let width = size_param(p, "width", C)?; + let height = size_param(p, "height", C)?; + if width.is_none() && height.is_none() { + return Err(bad(C, "give `width` or `height`")); + } + let proportional = switch_or(p, "proportional", false, C)?; + let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); + if let Some(w) = width { + q["width"] = json!(w); + } + if let Some(h) = height { + q["height"] = json!(h); + } + let mut xfs = vec![]; + for id in selected_roots(s)? { + if s.transform_box(&[id]).is_some() { + xfs.push((id, object_bounds_transform(s, &q, id)?)); + } + } + transform_each(s, "Set Size of Each", strokes, &xfs)?; + Ok(json!({ "count": xfs.len() })) +} + +/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, +/// chains included, among items of the same key (parent). A sweep along x: only the rects still +/// open where each one starts are compared with it. +fn overlapping(items: &[(K, Rect)]) -> Vec> { + fn root(up: &mut [usize], mut i: usize) -> usize { + while up[i] != i { + up[i] = up[up[i]]; + i = up[i]; + } + i + } + let mut up: Vec = (0..items.len()).collect(); + let mut order: Vec = (0..items.len()).collect(); + order.sort_by(|a, b| items[*a].1.x0.total_cmp(&items[*b].1.x0)); + let mut open: Vec = vec![]; + for i in order { + let (key, r) = (&items[i].0, items[i].1); + open.retain(|&j| items[j].1.x1 >= r.x0); + for &j in &open { + let (k, o) = (&items[j].0, items[j].1); + if k == key && o.y0 <= r.y1 && r.y0 <= o.y1 { + let (a, b) = (root(&mut up, i), root(&mut up, j)); + up[a] = b; + } + } + open.push(i); + } + let mut sets: Vec> = vec![vec![]; items.len()]; + for i in 0..items.len() { + let r = root(&mut up, i); + sets[r].push(i); + } + sets.retain(|s| s.len() > 1); + sets.sort_by_key(|s| s.first().copied()); + sets +} + +fn group_overlapping(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.arrange.groupOverlapping"; + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + let items: Vec<(NodeId, (Option, Rect))> = + roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect(); + let keyed: Vec<(Option, Rect)> = items.iter().map(|(_, k)| *k).collect(); + let sets: Vec> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + if sets.is_empty() { + return Ok(json!({ "groups": [], "grouped": 0 })); + } + let grouped: std::collections::HashSet = sets.iter().flatten().copied().collect(); + let groups = s.edit("Group Overlapping Objects", |d, sel| { + // Every group at once: the members behind each front one go, then each front one is + // replaced by its group (one pass over the tree each, however many groups). + let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]); + for set in &sets { + let Some((&front, rest)) = set.split_last() else { continue }; + let children: Vec> = set.iter().filter_map(|id| d.node(*id).cloned().map(Arc::new)).collect(); + let gid = d.alloc_id(); + places.push((front, vec![Node::group(gid, children)])); + behind.extend_from_slice(rest); + groups.push(gid); + } + d.remove_many(&behind)?; + d.insert_beside(places, true)?; + sel.set(groups.iter().copied().chain(roots.iter().copied().filter(|id| !grouped.contains(id)))); + Ok(groups) + })?; + Ok(json!({ "groups": groups.iter().map(|i| i.0).collect::>(), "grouped": grouped.len() })) +} + +fn randomize_opacity(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.randomizeOpacity"; + let min = number_in(p, "min", 30.0, (0.0, 100.0), C)?; + let max = number_in(p, "max", 100.0, (0.0, 100.0), C)?; + if min > max { + return Err(bad(C, "`min` is greater than `max`")); + } + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let ids = checked_ids_or_selection(s, p, C)?; + if ids.is_empty() { + return Ok(json!({ "count": 0 })); + } + let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32); + s.edit("Randomize Opacity", |d, _| { + for id in &ids { + let o = rng.range(lo, hi); + if let Some(n) = d.node_mut(*id) { + n.opacity = o; + } + } + Ok(()) + })?; + Ok(json!({ "count": ids.len() })) +} + +/// An object Sort Objects sorts: its layer or group, its place in it, its box as +/// `object.setBounds` measures it and its opacity (%). +struct Sorted { + id: NodeId, + parent: Option, + slot: usize, + b: OrientedBox, + opacity: f64, +} + +/// Attribute `key` (one of [`SORT_KEYS`]) of `o`, the `i`th of the objects in stacking order. +fn attribute(key: &str, o: &Sorted, i: usize) -> f64 { + let r = o.b.rect; + // The top-left corner where `object.setBounds` places it (reference point 0). + let corner = o.b.to_doc() * Point::new(r.x0, r.y0); + match key { + "width" => r.width(), + "height" => r.height(), + "area" => r.width() * r.height(), + "x" => corner.x, + "y" => corner.y, + "opacity" => o.opacity, + _ => i as f64, + } +} + +fn sort(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.sort"; + let by = choice(p, C, "by", &SORT_KEYS)?.unwrap_or("area"); + let apply = choice(p, C, "apply", &SORT_KEYS)?.unwrap_or("stacking"); + let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending"); + let distribute = switch_or(p, "distribute", false, C)?; + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let ids = checked_ids_or_selection(s, p, C)?; + if ids.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + // The objects in stacking order, from the back (their index paths, found in one walk). + let paths = d.index_paths(ids.iter().copied()); + let mut placed: Vec<(&Vec, NodeId)> = ids.iter().filter_map(|id| Some((paths.get(id)?, *id))).collect(); + placed.sort_by(|a, b| a.0.cmp(b.0)); + let items: Vec = placed + .into_iter() + .filter_map(|(path, id)| { + let (&slot, up) = path.split_last()?; + let parent = if up.is_empty() { None } else { Some(d.node_at(up)?.id) }; + Some(Sorted { id, parent, slot, b: s.transform_box(&[id])?, opacity: f64::from(d.node(id)?.opacity) * 100.0 }) + }) + .collect(); + let keys: Vec = items.iter().enumerate().map(|(i, o)| attribute(by, o, i)).collect(); + // The objects in sorted order; equal keys keep their stacking order. + let mut rank: Vec = (0..items.len()).collect(); + match order { + "random" => rng.shuffle(&mut rank), + "descending" => rank.sort_by(|a, b| keys[*b].total_cmp(&keys[*a])), + _ => rank.sort_by(|a, b| keys[*a].total_cmp(&keys[*b])), + } + let count = json!({ "count": items.len() }); + if apply == "stacking" { + // Each layer or group's objects take its objects' places, from the back, in sorted order. + let mut groups: HashMap, Vec> = HashMap::new(); + for o in rank.iter().filter_map(|i| items.get(*i)) { + groups.entry(o.parent).or_default().push(o.slot); + } + if groups.values().all(|slots| slots.is_sorted()) { + return Ok(count); + } + s.edit("Sort Objects", |d, _| { + for (parent, from) in groups { + let ch = d.children_mut(parent)?; + let nodes: Vec> = from.iter().filter_map(|i| ch.get(*i).cloned()).collect(); + let mut to = from; + to.sort_unstable(); + for (slot, n) in to.into_iter().zip(nodes) { + if let Some(c) = ch.get_mut(slot) { + *c = n; + } + } + } + Ok(()) + })?; + return Ok(count); + } + // The values the objects get, smallest first: theirs, or evenly from the smallest to the largest. + let mut values: Vec = items.iter().enumerate().map(|(i, o)| attribute(apply, o, i)).collect(); + values.sort_by(f64::total_cmp); + if let (true, Some(&lo), Some(&hi)) = (distribute && values.len() > 1, values.first(), values.last()) { + let steps = (values.len() - 1) as f64; + values = (0..values.len()).map(|j| lo + (hi - lo) * j as f64 / steps).collect(); + } + let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect(); + if apply == "opacity" { + if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) { + return Ok(count); + } + s.edit("Sort Objects", |d, _| { + for (o, v) in &wanted { + if let Some(n) = d.node_mut(o.id) { + n.opacity = (v / 100.0) as f32; + } + } + Ok(()) + })?; + return Ok(count); + } + let mut xfs = Vec::with_capacity(wanted.len()); + for (o, v) in wanted { + let q = match apply { + "x" => json!({ "x": v, "reference": 0 }), + "y" => json!({ "y": v, "reference": 0 }), + "width" => json!({ "width": v, "strokes": strokes }), + "height" => json!({ "height": v, "strokes": strokes }), + // An area: both sides in proportion; an object without one keeps its size. + _ => { + let (w, h) = (o.b.rect.width(), o.b.rect.height()); + let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 }; + json!({ "width": w * k, "height": h * k, "strokes": strokes }) + } + }; + xfs.push((o.id, object_bounds_transform(s, &q, o.id)?)); + } + transform_each(s, "Sort Objects", strokes, &xfs)?; + Ok(count) +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs new file mode 100644 index 0000000000..85191935b2 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -0,0 +1,564 @@ +//! Arrange Tools' commands: the geometry each one leaves, one undo step each, when they are off, +//! and bad params refused without a change. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A new document whose new art has no stroke, so visual and geometric bounds agree. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool { + [(a.x0, b.0), (a.y0, b.1), (a.width(), b.2), (a.height(), b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +fn enabled(s: &Session, cmd: &str) -> bool { + s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled +} + +#[test] +fn grid_lays_objects_out_in_rows_and_columns_from_the_back() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 10.0); + let b = rect(&mut s, 300.0, 50.0, 40.0, 30.0); + let c = rect(&mut s, 10.0, 200.0, 10.0, 10.0); + let d = rect(&mut s, 50.0, 5.0, 30.0, 20.0); + select(&mut s, &[d, c, b, a]); + let n = steps(&s); + // Four objects: two columns. The grid starts at the selection's top-left (10, 5). + let r = s.execute("addon.arrange.grid", &json!({"gapX": 5, "gapY": 2})).unwrap(); + assert_eq!(r["count"], json!(4)); + assert_eq!(steps(&s), n + 1, "one undo step"); + // Columns 20 and 40 wide (the widest in each), rows 30 and 20 tall; each object centred. + assert!(near(bounds(&s, a), (10.0, 15.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (35.0, 5.0, 40.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (15.0, 42.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, d), (40.0, 37.0, 30.0, 20.0)), "{:?}", bounds(&s, d)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(bounds(&s, a), (100.0, 100.0, 20.0, 10.0))); +} + +#[test] +fn grid_lays_out_a_row_or_a_column_and_centres_on_the_artboard() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("addon.arrange.grid", &json!({"layout": "row"})).unwrap(); + assert!(near(bounds(&s, b), (30.0, 0.0, 20.0, 20.0)), "gapX defaults to 10"); + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapX": 4})).unwrap(); + assert!(near(bounds(&s, b), (0.0, 24.0, 20.0, 20.0)), "gapY follows gapX"); + // 20 × 44 centred on the 400 × 300 artboard. + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapY": 4, "centerOnArtboard": true})).unwrap(); + assert!(near(bounds(&s, a), (190.0, 128.0, 20.0, 20.0)), "{:?}", bounds(&s, a)); + // In place already: no step. + let n = steps(&s); + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapY": 4, "centerOnArtboard": true})).unwrap(); + assert_eq!(steps(&s), n); + // More columns than objects: one row. + s.execute("addon.arrange.grid", &json!({"columns": 50, "gapX": 0})).unwrap(); + assert!(near(bounds(&s, b), (210.0, 128.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn grid_measures_visual_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + s.execute("addon.arrange.grid", &json!({"layout": "row", "gapX": 0})).unwrap(); + // Visual boxes 24 wide, touching. + assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn swap_trades_places_and_optionally_sizes() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let c = rect(&mut s, 200.0, 200.0, 5.0, 5.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.swap")); + select(&mut s, &[a, b, c]); + assert!(!enabled(&s, "addon.arrange.swap")); + refuses(&mut s, "addon.arrange.swap", &[json!({})]); + select(&mut s, &[a, b]); + assert!(enabled(&s, "addon.arrange.swap")); + let n = steps(&s); + s.execute("addon.arrange.swap", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + // Centres (10, 5) and (120, 120) swap; sizes stay. + assert!(near(bounds(&s, a), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.swap", &json!({"size": true})).unwrap(); + assert!(near(bounds(&s, a), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (0.0, 0.0, 20.0, 10.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn swap_with_sizes_scales_strokes_as_asked() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2})).unwrap(); + let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width(); + s.execute("addon.arrange.swap", &json!({"size": true})).unwrap(); + assert_eq!((weight(&s, a), weight(&s, b)), (2.0, 2.0), "off by default (the preference)"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.swap", &json!({"size": true, "scaleStrokes": true})).unwrap(); + assert!((weight(&s, a) - 4.0).abs() < 1e-9 && (weight(&s, b) - 1.0).abs() < 1e-9, "{} {}", weight(&s, a), weight(&s, b)); +} + +#[test] +fn replace_puts_a_copy_of_the_top_object_in_each_place() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let top = rect(&mut s, 200.0, 200.0, 10.0, 5.0); + select(&mut s, &[top]); + assert!(!enabled(&s, "addon.arrange.replace")); + refuses(&mut s, "addon.arrange.replace", &[json!({})]); + select(&mut s, &[a, b, top]); + let n = steps(&s); + let r = s.execute("addon.arrange.replace", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 2); + let st = s.doc().unwrap(); + assert!(st.doc.node(a).is_none() && st.doc.node(b).is_none(), "replaced objects deleted"); + assert!(st.doc.node(top).is_some(), "the top object stays"); + assert_eq!(st.selection.objects, ids, "the copies are selected"); + // Kept size, centred on (10, 20) and (120, 120); each in its object's place (bottom, then middle). + assert!(near(bounds(&s, ids[0]), (5.0, 17.5, 10.0, 5.0)), "{:?}", bounds(&s, ids[0])); + assert!(near(bounds(&s, ids[1]), (115.0, 117.5, 10.0, 5.0)), "{:?}", bounds(&s, ids[1])); + let layer = &s.doc().unwrap().doc.layers[0]; + let order: Vec = layer.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, [ids[0], ids[1], top]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).is_some()); +} + +#[test] +fn replace_fits_the_copies_and_can_keep_the_originals() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + let top = rect(&mut s, 200.0, 200.0, 10.0, 5.0); + select(&mut s, &[a, top]); + let r = s.execute("addon.arrange.replace", &json!({"fit": "bounds", "keep": true})).unwrap(); + let copy = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(near(bounds(&s, copy), (0.0, 0.0, 20.0, 40.0)), "{:?}", bounds(&s, copy)); + let order: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, [a, copy, top], "kept: the copy goes right above it"); + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[a, top]); + let r = s.execute("addon.arrange.replace", &json!({"fit": "proportional"})).unwrap(); + let copy = NodeId(r["ids"][0].as_u64().unwrap()); + // 10 × 5 into 20 × 40: twice as large, centred on (10, 20). + assert!(near(bounds(&s, copy), (0.0, 15.0, 20.0, 10.0)), "{:?}", bounds(&s, copy)); +} + +#[test] +fn size_gives_each_object_a_width_and_height() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + select(&mut s, &[a, b]); + let n = steps(&s); + s.execute("addon.arrange.size", &json!({"width": 30})).unwrap(); + assert_eq!(steps(&s), n + 1); + // About each centre; the height stays. + assert!(near(bounds(&s, a), (-5.0, 0.0, 30.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (105.0, 100.0, 30.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.size", &json!({"width": 40, "proportional": true, "reference": 0})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("addon.arrange.size", &json!({"width": 10, "height": 12, "proportional": true, "reference": 8})).unwrap(); + assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a)); +} + +#[test] +fn bad_params_are_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + select(&mut s, &[a, b]); + refuses( + &mut s, + "addon.arrange.grid", + &[ + json!({"layout": "spiral"}), + json!({"columns": 0}), + json!({"columns": 1.5}), + json!({"columns": 1e12}), + json!({"gapX": 1e308}), + json!({"gapY": "10"}), + json!({"centerOnArtboard": "yes"}), + ], + ); + refuses(&mut s, "addon.arrange.swap", &[json!({"size": 1}), json!({"scaleStrokes": "no"})]); + refuses(&mut s, "addon.arrange.replace", &[json!({"fit": "stretch"}), json!({"keep": 0})]); + refuses( + &mut s, + "addon.arrange.size", + &[ + json!({}), + json!({"width": 0}), + json!({"height": -5}), + json!({"width": 1e308}), + json!({"width": "10"}), + json!({"width": 10, "reference": 9}), + json!({"width": 10, "proportional": "yes"}), + ], + ); +} + +#[test] +fn off_without_a_selection() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 20.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + for c in [ + "addon.arrange.grid", + "addon.arrange.swap", + "addon.arrange.replace", + "addon.arrange.size", + "addon.arrange.groupOverlapping", + "addon.arrange.randomizeOpacity", + "addon.arrange.sort", + ] { + assert!(!enabled(&s, c), "{c}"); + } + assert!(!enabled(&Session::new(), "addon.arrange.swap")); +} + +fn ids_of(v: &Value) -> Vec { + v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn children(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn group_overlapping_groups_chains_and_leaves_loners() { + let mut s = session(); + // a–b–c a chain (c only touches b), d alone, e over f. + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + let e = rect(&mut s, 100.0, 100.0, 30.0, 30.0); + let c = rect(&mut s, 35.0, 0.0, 10.0, 20.0); + let f = rect(&mut s, 110.0, 110.0, 5.0, 5.0); + select(&mut s, &[a, b, c, d, e, f]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["grouped"], json!(5)); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 2); + assert_eq!(children(&s, groups[0]), [a, b, c], "members keep their stacking order"); + assert_eq!(children(&s, groups[1]), [e, f]); + // Each group where its frontmost member was: a d [abc] [ef] → d, group(abc) above it, then (ef). + let layer: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [d, groups[0], groups[1]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&d) && sel.len() == 3, "{sel:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 6); +} + +#[test] +fn group_overlapping_keeps_layers_apart_and_measures_visual_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let gap = rect(&mut s, 22.0, 0.0, 20.0, 20.0); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[a, gap, other]); + // 2 pt apart: nothing overlaps within a layer, and a and `other` are in different layers. + let n = steps(&s); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "no groups, no step"); + // A 4 pt stroke reaches 2 pt out: the two in the first layer now touch. + select(&mut s, &[a, gap]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + select(&mut s, &[a, gap, other]); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, gap]); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn group_overlapping_is_off_with_one_object_and_scales_to_many() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.groupOverlapping")); + // A long row of pairs: each pair overlaps, neighbouring pairs don't. + let rects: Vec<(usize, Rect)> = + (0..4000).map(|i| (0, Rect::new(i as f64 * 10.0, 0.0, i as f64 * 10.0 + if i % 2 == 0 { 12.0 } else { 3.0 }, 5.0))).collect(); + let sets = super::overlapping(&rects); + assert_eq!(sets.len(), 2000); + assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1)); +} + +fn opacity(s: &Session, id: NodeId) -> f32 { + s.doc().unwrap().doc.node(id).unwrap().opacity +} + +#[test] +fn randomize_opacity_gives_each_object_its_own_opacity_within_the_range() { + let mut s = session(); + let ids: Vec = (0..20).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect(); + select(&mut s, &ids); + let n = steps(&s); + let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap(); + assert_eq!(r["count"], json!(20)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let first: Vec = ids.iter().map(|id| opacity(&s, *id)).collect(); + assert!(first.iter().all(|o| (0.3..=0.6).contains(o)), "{first:?}"); + assert!(first.windows(2).any(|w| w[0] != w[1]), "each its own: {first:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| opacity(&s, *id) == 1.0), "undone"); + // The same seed repeats them; another seed doesn't. + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap(); + assert_eq!(ids.iter().map(|id| opacity(&s, *id)).collect::>(), first); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 8})).unwrap(); + assert_ne!(ids.iter().map(|id| opacity(&s, *id)).collect::>(), first); + // Defaults 30 to 100; min = max gives every object that opacity. + s.execute("addon.arrange.randomizeOpacity", &json!({})).unwrap(); + assert!(ids.iter().all(|id| (0.3..=1.0).contains(&opacity(&s, *id)))); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 45, "max": 45})).unwrap(); + assert!(ids.iter().all(|id| opacity(&s, *id) == 0.45)); +} + +#[test] +fn randomize_opacity_takes_ids_and_leaves_the_rest() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0); + select(&mut s, &[a, b]); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 20.0, 0.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(!enabled(&s, "addon.arrange.randomizeOpacity")); + s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [c.0], "min": 10, "max": 10})).unwrap(); + assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (1.0, 1.0, 0.1)); + // A group takes one opacity of its own; the objects inside keep theirs. + select(&mut s, &[g]); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 20, "max": 20})).unwrap(); + assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0)); +} + +#[test] +fn randomize_opacity_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + select(&mut s, &[a]); + refuses( + &mut s, + "addon.arrange.randomizeOpacity", + &[ + json!({"min": -1}), + json!({"max": 101}), + json!({"min": 80, "max": 20}), + json!({"min": 1e308}), + json!({"max": "50"}), + json!({"seed": -1}), + json!({"seed": 1.5}), + json!({"seed": "x"}), + json!({"ids": [999_999]}), + json!({"ids": "x"}), + ], + ); + let e = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 80, "max": 20})).unwrap_err().to_string(); + assert!(e.contains("`min` is greater than `max`"), "{e}"); +} + +fn layer_order(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +/// Three squares: `a` 30 wide at x 0, `b` 10 wide at x 100, `c` 20 wide at x 200, all selected. +fn squares(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let a = rect(s, 0.0, 0.0, 30.0, 30.0); + let b = rect(s, 100.0, 0.0, 10.0, 10.0); + let c = rect(s, 200.0, 0.0, 20.0, 20.0); + select(s, &[a, b, c]); + (a, b, c) +} + +#[test] +fn sort_by_area_lines_objects_up_along_x() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + let n = steps(&s); + let r = s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x"})).unwrap(); + assert_eq!(r["count"], json!(3)); + assert_eq!(steps(&s), n + 1, "one undo step"); + // Smallest first: b, c, a take the left edges 0, 100, 200; y stays. + assert!(near(bounds(&s, b), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (100.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, a), (200.0, 0.0, 30.0, 30.0)), "{:?}", bounds(&s, a)); + // Large to small: a, c, b. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!((bounds(&s, a).x0, bounds(&s, c).x0, bounds(&s, b).x0), (0.0, 100.0, 200.0)); + // Already in order: no step. + let n = steps(&s); + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!(steps(&s), n); +} + +#[test] +fn sort_distributes_values_evenly() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 10.0, 50.0, 10.0, 50.0); + let c = rect(&mut s, 200.0, 0.0, 10.0, 20.0); + select(&mut s, &[a, b, c]); + // Left edges 0, 10, 200 step evenly: 0, 100, 200. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "x", "distribute": true})).unwrap(); + assert_eq!((bounds(&s, a).x0, bounds(&s, b).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0)); + // Heights that step evenly with x (10 to 50), each about its centre. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "height", "distribute": true})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (100.0, 60.0, 10.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (200.0, -15.0, 10.0, 50.0)), "{:?}", bounds(&s, c)); +} + +#[test] +fn sort_restacks_within_each_layer() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Largest at the back. + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "stacking", "order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [a, c, b]); + s.execute("addon.arrange.sort", &json!({})).unwrap(); + assert_eq!(layer_order(&s), [b, c, a], "by area, small to large, into the stacking order by default"); + // An object in another layer keeps its layer; the others trade places among themselves. + s.execute("layer.new", &json!({})).unwrap(); + let big = rect(&mut s, 0.0, 100.0, 50.0, 50.0); + select(&mut s, &[a, b, c, big]); + s.execute("addon.arrange.sort", &json!({"order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [a, c, b]); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.layer_of(big), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn sort_by_stacking_and_opacity() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Back to front a, b, c; reversed: c, b, a take the left edges 0, 100, 200. + s.execute("addon.arrange.sort", &json!({"by": "stacking", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!((bounds(&s, c).x0, bounds(&s, b).x0, bounds(&s, a).x0), (0.0, 100.0, 200.0)); + for (id, o) in [(a, 20), (b, 80), (c, 50)] { + s.execute("object.setProps", &json!({"ids": [id.0], "opacity": o})).unwrap(); + } + select(&mut s, &[a, b, c]); + let opacity = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().opacity; + // By x, large to small: a (x 200) gets the least opacity, then b, then c. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "opacity", "order": "descending"})).unwrap(); + assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (0.2, 0.5, 0.8)); + // By opacity into the stacking order, large to small: the most opaque at the back. + s.execute("addon.arrange.sort", &json!({"by": "opacity", "order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [c, b, a]); +} + +#[test] +fn sort_by_area_into_areas_scales_in_proportion() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Areas 900, 100, 400 by x: a (x 0) 100, b 500, c 900. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "area", "distribute": true})).unwrap(); + let side = |s: &Session, id| bounds(s, id).width(); + assert!((side(&s, a) - 10.0).abs() < 1e-6 && (side(&s, b) - 500f64.sqrt()).abs() < 1e-6 && (side(&s, c) - 30.0).abs() < 1e-6); + assert!((bounds(&s, b).height() - 500f64.sqrt()).abs() < 1e-6, "in proportion"); +} + +#[test] +fn sort_in_random_order_repeats_with_a_seed() { + let mut s = session(); + let ids: Vec = (0..12).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect(); + select(&mut s, &ids); + s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap(); + let first = layer_order(&s); + assert_ne!(first, ids, "shuffled"); + let mut sorted = first.clone(); + sorted.sort_by_key(|i| i.0); + assert_eq!(sorted, ids, "the same objects"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_order(&s), ids); + s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap(); + assert_eq!(layer_order(&s), first, "the same seed, the same order"); +} + +#[test] +fn sort_takes_ids_and_refuses_bad_params() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.sort")); + s.execute("addon.arrange.sort", &json!({"ids": [b.0, a.0], "apply": "x"})).unwrap(); + assert_eq!((bounds(&s, b).x0, bounds(&s, a).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0), "c is left alone"); + select(&mut s, &[a, b, c]); + refuses( + &mut s, + "addon.arrange.sort", + &[ + json!({"by": "color"}), + json!({"apply": 3}), + json!({"order": "up"}), + json!({"distribute": "yes"}), + json!({"seed": -1}), + json!({"seed": 0.5}), + json!({"scaleStrokes": 1}), + json!({"ids": "x"}), + json!({"ids": [999_999]}), + ], + ); +} diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs new file mode 100644 index 0000000000..b65fc75ac3 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -0,0 +1,365 @@ +//! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the +//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path +//! Pieces, and its text tools ([`text`]). Its panel and its submenu, Object › Plug-ins › Artwork +//! Cleanup, are the UI's. + +mod checks; +#[cfg(test)] +mod tests; +mod text; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, SubPath}; +use vectorcraft_pathops::addons as po; + +use self::checks::{Kind, MAX_OBJECTS, Outcome, Scope, set_path}; +use super::super::edit::selected_roots; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// Simplify Anchors' tolerance by default. +const TOLERANCE: f64 = 20.0; +/// Rejoin Path Pieces' gap by default, and the widest (pt). +const GAP: f64 = 0.1; +const MAX_GAP: f64 = 6.0; +/// Most anchors Simplify Anchors takes at once. +const MAX_ANCHORS: usize = 2_000_000; +/// Most rounds of fixes `addon.cleanup.fix` runs. +const FIX_ROUNDS: usize = 3; +/// Most ids a finding lists (its count counts them all). +const MAX_LISTED: usize = 1000; + +pub fn specs() -> Vec { + let mut v = vec![ + cmd!( + "addon.cleanup.simplify", + "Simplify Anchors (Keep Shape)…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay → {ids, before, after} anchor counts", + has_selection, + simplify + ), + cmd!( + query "addon.cleanup.check", + "Health Check", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), kinds?: [kind…] (default: all: emptyText, strayPoints (paths of one anchor), unpainted, zeroOpacity, duplicateObjects (a path stacked on an identical one, or type on the same type within 1 pt), offArtboard, duplicateAnchors (neighbours within 0.01 pt), tinyHandles (under 0.01 pt), collinearAnchors (corners on a straight run, turning less than sine 0.005), nearPoints (anchors within 0.01 pt of other paths' anchors), nearlyClosed (ends within 0.01 pt), filledOpenPaths (filled, unstroked open paths), needlessClipGroups (an unpainted clip that clips nothing, hides everything, or is a rectangle round all its art), needlessCompounds (one path or none), needlessGroups (one member or none, nothing of their own), emptyArtboards (the document only))} find issues without changing anything; locked and hidden objects are left out → {scope, total, findings: [{kind, label, count, ids (the objects, at most 1000), artboards (indexes)}]} for the kinds found", + has_doc, + check + ), + cmd!( + query "addon.cleanup.show", + "Show Issue", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{kind: kind (see addon.cleanup.check), scope?: \"selection\"|\"document\"} select the objects with that issue → {kind, count, ids, artboards}", + has_doc, + show + ), + cmd!( + "addon.cleanup.fix", + "Fix All Issues", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}", + has_doc, + fix + ), + cmd!( + "addon.cleanup.deepUngroup", + "Deep Ungroup…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in → {ids (the objects left, selected), ungrouped (groups)}", + has_selection, + deep_ungroup + ), + cmd!( + "addon.cleanup.rejoin", + "Rejoin Path Pieces…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}", + has_selection, + rejoin + ), + ]; + v.extend(text::specs()); + v +} + +/// The paths (not guides) under `roots`, compound path members included. +fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { + let mut out = vec![]; + for n in roots.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { guide: false, .. }) { + out.push(c.id); + } + }); + } + out +} + +fn simplify(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.simplify"; + let tolerance = number_or(p, "tolerance", TOLERANCE, C)?; + if !(1.0..=100.0).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 1 to 100")); + } + let protect = switch_or(p, "protectCorners", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect(); + let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum(); + if before > MAX_ANCHORS { + return Err(EngineError::Other("Simplify Anchors: the paths have too many anchors to simplify at once".into())); + } + let changed: Vec<(NodeId, PathData)> = paths + .iter() + .filter_map(|(id, path)| { + let np = po::simplify_keep_shape(path, tolerance * po::PT_PER_TOLERANCE, protect); + (np != **path).then_some((*id, np)) + }) + .collect(); + let removed: usize = changed.iter().filter_map(|(id, np)| Some(d.node(*id)?.path_data()?.anchor_count().saturating_sub(np.anchor_count()))).sum(); + let after = before.saturating_sub(removed); + // When no anchor can go, the document and its undo history stay as they are. + if !changed.is_empty() { + s.edit("Simplify Anchors (Keep Shape)", |d, sel| { + for (id, np) in changed { + // The anchors left are new ones: the path is selected whole. + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "before": before, "after": after })) +} + +/// The scope a check, show or fix request names (by default the selection, or the document while +/// nothing is selected) and its name. +fn scope_of(s: &Session, p: &Value, cmd: &str) -> Result<(Scope, &'static str)> { + let roots = selected_roots(s)?; + match text_param(p, "scope", cmd)? { + Some("document") => Ok((Scope::Document, "document")), + None if roots.is_empty() => Ok((Scope::Document, "document")), + Some("selection") if roots.is_empty() => Err(bad(cmd, "nothing selected")), + Some("selection") | None => Ok((Scope::Objects(roots), "selection")), + Some(other) => Err(bad(cmd, format!("`scope` must be \"selection\" or \"document\", not {other:?}"))), + } +} + +/// The kinds a request names (all by default), in the order Fix runs them. +fn kinds_of(p: &Value, cmd: &str) -> Result> { + let given: Vec = match p.get("kinds") { + None | Some(Value::Null) => return Ok(Kind::ALL.to_vec()), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().and_then(Kind::parse).ok_or_else(|| bad(cmd, format!("unknown issue kind {v}")))).collect::>()? + } + Some(_) => return Err(bad(cmd, "`kinds` must be a list of issue kinds")), + }; + Ok(Kind::ALL.into_iter().filter(|k| given.contains(k)).collect()) +} + +/// Kind `kind`'s fix run on a copy of the active document: what Fix would change. +fn dry_run(s: &Session, kind: Kind, scope: &Scope) -> Result { + let st = s.doc()?; + let (mut d, mut sel, mut scope) = ((*st.doc).clone(), st.selection.clone(), scope.clone()); + kind.fix(&mut d, &mut sel, &mut scope) +} + +fn finding(kind: Kind, o: &Outcome) -> Value { + let ids: Vec = o.ids.iter().take(MAX_LISTED).map(|i| i.0).collect(); + json!({ "kind": kind.id(), "label": kind.label(), "count": o.count, "ids": ids, "artboards": o.artboards }) +} + +fn check(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.check"; + let (scope, name) = scope_of(s, p, C)?; + let mut findings = vec![]; + let mut total = 0; + for kind in kinds_of(p, C)? { + let o = dry_run(s, kind, &scope)?; + if o.count > 0 { + total += o.count; + findings.push(finding(kind, &o)); + } + } + Ok(json!({ "scope": name, "total": total, "findings": findings })) +} + +fn show(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.show"; + let id = text_param(p, "kind", C)?.ok_or_else(|| bad(C, "missing `kind`"))?; + let kind = Kind::parse(id).ok_or_else(|| bad(C, format!("unknown issue kind {id:?}")))?; + let (scope, _) = scope_of(s, p, C)?; + let o = dry_run(s, kind, &scope)?; + if o.count == 0 { + return Err(EngineError::Other("None of these issues are left: check again".into())); + } + // Artboards are no objects to select: the selection stays as it is for them. + let ids = o.ids.clone(); + if !ids.is_empty() { + s.select(|_, sel| sel.set(ids))?; + } + Ok(finding(kind, &o)) +} + +fn fix(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.fix"; + let (mut scope, name) = scope_of(s, p, C)?; + let kinds = kinds_of(p, C)?; + // Fixed on a copy, kind after kind (what one leaves, the next cleans up), then kept as one step. + let st = s.doc()?; + let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone()); + let mut fixed = Map::new(); + let mut total = 0; + // A fix can leave issues for a kind that ran before it (groups unwrapped side by side may hold + // duplicates): the kinds run again, a few rounds at most, until a round finds nothing. + for _ in 0..FIX_ROUNDS { + let before = total; + for &kind in &kinds { + let o = kind.fix(&mut d, &mut sel, &mut scope)?; + if o.count > 0 { + total += o.count; + let n = fixed.get(kind.id()).and_then(Value::as_u64).unwrap_or(0); + fixed.insert(kind.id().into(), json!(n + o.count as u64)); + } + } + if total == before { + break; + } + } + // With nothing to fix, the document and its undo history stay as they are. + if total > 0 { + sel.prune(&d); + s.edit("Fix Issues", |doc, selection| { + *doc = d; + *selection = sel; + Ok(()) + })?; + } + Ok(json!({ "scope": name, "total": total, "fixed": fixed })) +} + +/// Is `n` a group Deep Ungroup takes apart (a clipping group only with `clips`)? +fn ungroupable(n: &Node, clips: bool) -> bool { + matches!(n.kind, NodeKind::Group { clip, .. } if clips || !clip) +} + +/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts +/// the groups. Members take on the opacity of the groups they were in, and a clipping path +/// becomes a plain path. +fn flatten(n: Node, clips: bool, out: &mut Vec, count: &mut usize) { + if !ungroupable(&n, clips) { + out.push(n); + return; + } + let NodeKind::Group { children, clip } = &n.kind else { return }; + *count += 1; + for (k, c) in children.iter().enumerate() { + let mut c = (**c).clone(); + if *clip + && k == 0 + && let NodeKind::Path { clipping, .. } = &mut c.kind + { + *clipping = false; + } + c.opacity *= n.opacity; + flatten(c, clips, out, count); + } +} + +fn deep_ungroup(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.deepUngroup"; + let clips = switch_or(p, "includeClipGroups", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let (mut items, mut selected, mut count) = (vec![], vec![], 0); + for id in &roots { + match d.node(*id).filter(|n| ungroupable(n, clips)) { + Some(n) => { + let mut out = vec![]; + flatten(n.clone(), clips, &mut out, &mut count); + selected.extend(out.iter().map(|n| n.id)); + items.push((*id, out)); + } + None => selected.push(*id), + } + } + // With no group to take apart, the document and its undo history stay as they are. + if !items.is_empty() { + let ids = selected.clone(); + s.edit("Deep Ungroup", |d, sel| { + d.insert_beside(items, true)?; + sel.set(ids); + Ok(()) + })?; + } + Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::>(), "ungrouped": count })) +} + +/// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order +/// (compound path members, clipping paths and guides stay out). +fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> { + fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) { + match &n.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } => { + if let [sp] = path.subpaths.as_slice() + && !sp.closed + { + out.push((n.id, sp.clone())); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)), + _ => {} + } + } + let mut out = vec![]; + roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); + let editable = d.editable(); + out.retain(|(id, _)| editable(*id)); + out +} + +fn rejoin(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.rejoin"; + let gap = number_or(p, "gap", GAP, C)?; + if !(0.0..=MAX_GAP).contains(&gap) { + return Err(bad(C, "`gap` must be from 0 to 6 pt")); + } + let roots = checked_ids_or_selection(s, p, C)?; + let found = pieces(&s.doc()?.doc, &roots); + if found.len() > MAX_OBJECTS { + return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into())); + } + let subpaths: Vec = found.iter().map(|(_, sp)| sp.clone()).collect(); + // Each chain becomes its topmost piece (the last in paint order); the others go. + let (mut kept, mut gone) = (vec![], vec![]); + for j in po::rejoin(&subpaths, gap) { + let ids: Vec = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect(); + let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue }; + gone.extend(ids.into_iter().filter(|id| *id != top)); + kept.push((top, j.path)); + } + if !kept.is_empty() { + let ids: Vec = kept.iter().map(|k| k.0).collect(); + s.edit("Rejoin Path Pieces", |d, sel| { + for (id, sp) in &kept { + set_path(d, *id, PathData::single(sp.clone())); + } + d.remove_many(&gone)?; + sel.set(ids); + Ok(()) + })?; + } + let ids: Vec = kept.iter().map(|k| k.0.0).collect(); + Ok(json!({ "ids": ids, "joined": kept.len(), "removed": gone.len() })) +} diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs new file mode 100644 index 0000000000..c3abd029be --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -0,0 +1,483 @@ +//! Document Health Check: the kinds of issue Artwork Cleanup looks for, and how each is fixed. A +//! check runs a kind's fix on a copy of the document, so what a check finds is what Fix changes. + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_color::BlendMode; +use vectorcraft_doc::appearance::AppearanceItem; +use vectorcraft_doc::{Appearance, Document, Knockout, Node, NodeExtras, NodeId, NodeKind, Selection, SymbolBoxes}; +use vectorcraft_geom::{PathData, Point, Rect}; +use vectorcraft_pathops::addons as po; + +use super::super::super::edit::outermost; +use super::super::super::layer::empty_artboards; +use crate::Result; + +/// Sine of the turn below which an anchor on a straight run is collinear. +const COLLINEAR: f64 = 0.005; +/// Distance (pt) within which anchors coincide, handles are tiny and path ends meet. +const NEAR: f64 = 0.01; +/// Most objects a check looks at; the rest of a larger document is left as it is. +pub(super) const MAX_OBJECTS: usize = 250_000; +/// Most anchors Near Anchors compares. +const MAX_ANCHORS: usize = 1_000_000; +/// Most rounds of unwrapping nested groups. +const MAX_PASSES: usize = 64; + +/// One kind of issue. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Kind { + EmptyText, + StrayPoints, + Unpainted, + ZeroOpacity, + DuplicateObjects, + OffArtboard, + DuplicateAnchors, + TinyHandles, + CollinearAnchors, + NearPoints, + NearlyClosed, + FilledOpenPaths, + NeedlessClipGroups, + NeedlessCompounds, + NeedlessGroups, + EmptyArtboards, +} + +impl Kind { + /// Every kind, in the order Fix runs them (removing art first can leave groups to unwrap). + pub(super) const ALL: [Kind; 16] = [ + Kind::EmptyText, + Kind::StrayPoints, + Kind::Unpainted, + Kind::ZeroOpacity, + Kind::DuplicateObjects, + Kind::OffArtboard, + Kind::DuplicateAnchors, + Kind::TinyHandles, + Kind::CollinearAnchors, + Kind::NearPoints, + Kind::NearlyClosed, + Kind::FilledOpenPaths, + Kind::NeedlessClipGroups, + Kind::NeedlessCompounds, + Kind::NeedlessGroups, + Kind::EmptyArtboards, + ]; + + /// (id, label) of the kind. + fn names(self) -> (&'static str, &'static str) { + match self { + Kind::EmptyText => ("emptyText", "Empty Text"), + Kind::StrayPoints => ("strayPoints", "Stray Points"), + Kind::Unpainted => ("unpainted", "Unpainted Objects"), + Kind::ZeroOpacity => ("zeroOpacity", "Zero-Opacity Objects"), + Kind::DuplicateObjects => ("duplicateObjects", "Duplicate Objects"), + Kind::OffArtboard => ("offArtboard", "Off-Artboard Art"), + Kind::DuplicateAnchors => ("duplicateAnchors", "Duplicate Anchors"), + Kind::TinyHandles => ("tinyHandles", "Tiny Handles"), + Kind::CollinearAnchors => ("collinearAnchors", "Collinear Anchors"), + Kind::NearPoints => ("nearPoints", "Nearly Coincident Anchors"), + Kind::NearlyClosed => ("nearlyClosed", "Nearly Closed Paths"), + Kind::FilledOpenPaths => ("filledOpenPaths", "Filled Open Paths"), + Kind::NeedlessClipGroups => ("needlessClipGroups", "Needless Clipping Groups"), + Kind::NeedlessCompounds => ("needlessCompounds", "Needless Compound Paths"), + Kind::NeedlessGroups => ("needlessGroups", "Needless Groups"), + Kind::EmptyArtboards => ("emptyArtboards", "Empty Artboards"), + } + } + + pub(super) fn id(self) -> &'static str { + self.names().0 + } + + pub(super) fn label(self) -> &'static str { + self.names().1 + } + + pub(super) fn parse(id: &str) -> Option { + Kind::ALL.into_iter().find(|k| k.id() == id) + } + + /// Fix this kind of issue in `scope` of `d` → what changed. + pub(super) fn fix(self, d: &mut Document, sel: &mut Selection, scope: &mut Scope) -> Result { + match self { + Kind::DuplicateAnchors => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::merge_duplicate_anchors(sp, NEAR)).sum()), + Kind::TinyHandles => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::retract_tiny_handles(sp, NEAR)).sum()), + Kind::CollinearAnchors => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::remove_collinear_anchors(sp, COLLINEAR)).sum()), + Kind::NearlyClosed => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| usize::from(po::close_nearly_closed(sp, NEAR))).sum()), + Kind::FilledOpenPaths => reshape(d, scope, close_filled), + Kind::NearPoints => near_points(d, scope), + Kind::EmptyArtboards => artboards(d, sel, scope), + _ => restructure(d, scope, self), + } + } + + /// What replaces object `n` (at `place`) when it is this kind of issue: nothing to remove it, + /// its members to unwrap it. `None` when it isn't one. + fn replacement(self, cx: &Context, n: &Node, place: Place) -> Option> { + let removable = !place.clips && !is_guide_or_clip(n); + let gone = |is: bool| is.then(Vec::new); + match self { + Kind::EmptyText => gone(matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())), + Kind::StrayPoints => gone(removable && matches!(&n.kind, NodeKind::Path { path, .. } if path.anchor_count() <= 1)), + Kind::Unpainted => gone(removable && !place.in_compound && is_shape(n) && !is_painted(&n.appearance)), + Kind::ZeroOpacity => gone(removable && !place.in_compound && n.opacity <= 0.0), + Kind::DuplicateObjects => gone(removable && duplicates_the_one_below(cx.d, n)), + Kind::OffArtboard => gone(place.top && !is_guide_or_clip(n) && off_artboards(cx, n)), + Kind::NeedlessGroups => needless_group(n), + Kind::NeedlessCompounds => needless_compound(n), + Kind::NeedlessClipGroups => needless_clip_group(cx, n), + _ => None, + } + } +} + +/// What a fix changed (or a check found): how many issues, the objects they are on and the +/// artboards (by index) they are. +#[derive(Clone, Debug, Default)] +pub(super) struct Outcome { + pub count: usize, + pub ids: Vec, + pub artboards: Vec, +} + +/// What a check looks at: the whole document, or the objects given and what is inside them. +#[derive(Clone, Debug)] +pub(super) enum Scope { + Document, + Objects(Vec), +} + +/// Where an object sits. +#[derive(Clone, Copy, Default)] +struct Place { + /// A member of a compound path. + in_compound: bool, + /// The clipping path of its group or layer. + clips: bool, + /// A top-level object of the scope (on a layer, or given). + top: bool, +} + +/// The document a pass looks at, with its symbols measured once. +struct Context<'a> { + d: &'a Document, + symbols: SymbolBoxes<'a>, +} + +/// The visible, unlocked objects in `scope` with where they sit, in paint order: groups, layers, +/// clip groups and compound paths are looked into; live and generated art (blends, envelopes, +/// graphs, symbols…) is taken as it is. +fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> { + let mut out = vec![]; + let top = Place { top: true, ..Place::default() }; + match scope { + Scope::Document => d.layers.iter().for_each(|l| visit(l, top, &mut out)), + Scope::Objects(ids) => ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, top, &mut out)), + } + let editable = d.editable(); + out.retain(|(n, _)| editable(n.id)); + out +} + +fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) { + if !n.visible || n.locked || out.len() >= MAX_OBJECTS { + return; + } + let inner = |clip: bool, i: usize, top: bool| Place { clips: clip && i == 0, top, in_compound: false }; + match &n.kind { + // A layer's objects are top-level ones. + NodeKind::Layer { children, clip, .. } => children.iter().enumerate().for_each(|(i, c)| visit(c, inner(*clip, i, true), out)), + NodeKind::Group { children, clip } if !is_generated(n) => { + out.push((n, place)); + children.iter().enumerate().for_each(|(i, c)| visit(c, inner(*clip, i, false), out)); + } + NodeKind::Compound { children, .. } => { + out.push((n, place)); + children.iter().for_each(|c| visit(c, Place { in_compound: true, ..Place::default() }, out)); + } + _ => out.push((n, place)), + } +} + +/// A group that stands for live or generated art: its members aren't loose art to clean. +fn is_generated(n: &Node) -> bool { + let e = n.extras(); + e.graph.is_some() || e.shaper.is_some() || e.dimension.is_some() || e.objects_on_path.is_some() || e.live_paint_gaps.is_some() || e.compound_shape +} + +fn is_guide_or_clip(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. }) +} + +fn is_shape(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) +} + +fn is_painted(a: &Appearance) -> bool { + a.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0, + }) +} + +/// A container with nothing of its own to show: full opacity, normal blending, no fill, stroke, +/// effect, mask, knockout or anything else attached. +fn is_plain(n: &Node) -> bool { + n.opacity >= 1.0 + && n.blend == BlendMode::Normal + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && !n.isolate + && n.knockout == Knockout::Neutral + && *n.extras() == NodeExtras::default() +} + +/// Is `n` a plain path or type object (full opacity, normal blending) that doubles the object just +/// below it? +fn duplicates_the_one_below(d: &Document, n: &Node) -> bool { + if n.opacity < 1.0 || n.blend != BlendMode::Normal { + return false; + } + let below = d.position(n.id).and_then(|(parent, i, _)| d.children(parent)?.get(i.checked_sub(1)?).cloned()); + below.is_some_and(|b| { + b.visible + && same_art(&b.kind, &n.kind) + && b.appearance == n.appearance + && b.opacity == n.opacity + && b.blend == n.blend + && b.extras() == n.extras() + }) +} + +/// Distance (pt) within which doubled type counts as stacked: text set twice from a PDF or an old +/// file, or for a fake bold, is often a fraction of a point off. +const DOUBLED_TYPE: f64 = 1.0; + +/// The same path, or the same type (text, styles, size and turn) within [`DOUBLED_TYPE`] of it. +fn same_art(a: &NodeKind, b: &NodeKind) -> bool { + match (a, b) { + (NodeKind::Path { .. }, NodeKind::Path { .. }) => a == b, + (NodeKind::Text(a), NodeKind::Text(b)) => { + let ([a0, a1, a2, a3, ax, ay], [b0, b1, b2, b3, bx, by]) = (a.xf.as_coeffs(), b.xf.as_coeffs()); + [a0, a1, a2, a3] == [b0, b1, b2, b3] && (ax - bx).hypot(ay - by) <= DOUBLED_TYPE && { + // `b` placed on `a`, with `a`'s layout caches (they are in document space). + let mut moved = (**b).clone(); + moved.xf = a.xf; + moved.cached_bounds = a.cached_bounds; + moved.cached_baselines.clone_from(&a.cached_baselines); + **a == moved + } + } + _ => false, + } +} + +fn inside(a: Rect, b: Rect) -> bool { + a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1 +} + +fn meets(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Does `n` lie wholly off every artboard (a document without artboards has none off them)? +fn off_artboards(cx: &Context, n: &Node) -> bool { + let Some(b) = n.visual_bounds_with(&cx.symbols) else { return false }; + // As Delete Empty Artboards measures: a millionth of a point covers rounding at the edges. + !cx.d.artboards.is_empty() && !cx.d.artboards.iter().any(|a| meets(a.rect.inflate(1e-6, 1e-6), b)) +} + +/// A plain group of one member or none: its member, or nothing. +fn needless_group(n: &Node) -> Option> { + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + (children.len() <= 1 && is_plain(n)).then(|| children.iter().map(|c| (**c).clone()).collect()) +} + +/// A compound path of one path or none: that path, painted as the compound was, or nothing. +fn needless_compound(n: &Node) -> Option> { + let NodeKind::Compound { children, rule } = &n.kind else { return None }; + let mut path = match children.as_slice() { + [] => return Some(vec![]), + [one] => (**one).clone(), + _ => return None, + }; + let NodeKind::Path { rule: r, .. } = &mut path.kind else { return None }; + *r = *rule; + path.appearance = n.appearance.clone(); + path.opacity = n.opacity; + path.blend = n.blend; + path.extras = n.extras.clone(); + Some(vec![path]) +} + +/// A plain clip group whose unpainted clipping path changes nothing: it clips nothing or lies wholly +/// away from its art (nothing shows: nothing is left), or it is a rectangle around all its art (its +/// art is left). +fn needless_clip_group(cx: &Context, n: &Node) -> Option> { + let NodeKind::Group { children, clip: true } = &n.kind else { return None }; + if !is_plain(n) { + return None; + } + let Some((clip, art)) = children.split_first() else { return Some(vec![]) }; + let paint = clip.clip_paint(); + if paint.fill.is_some() || paint.stroke.is_some() { + return None; + } + let clip_box = clip.geometric_bounds()?; + let art_box = art.iter().filter_map(|a| a.visual_bounds_with(&cx.symbols)).reduce(|a, b| a.union(b)); + match art_box { + None => Some(vec![]), + Some(b) if !meets(clip_box, b) => Some(vec![]), + Some(b) if is_rectangle(clip) && inside(b, clip_box.inflate(1e-6, 1e-6)) => Some(art.iter().map(|a| (**a).clone()).collect()), + _ => None, + } +} + +/// Is `n` a path drawing a square-to-the-page rectangle: four corners on its bounds, no curves? +fn is_rectangle(n: &Node) -> bool { + let NodeKind::Path { path, .. } = &n.kind else { return false }; + let (Some(b), [sp]) = (path.bounds(), path.subpaths.as_slice()) else { return false }; + let corner = |p: Point| ((p.x - b.x0).abs() < 1e-6 || (p.x - b.x1).abs() < 1e-6) && ((p.y - b.y0).abs() < 1e-6 || (p.y - b.y1).abs() < 1e-6); + sp.closed && sp.anchors.len() == 4 && sp.anchors.iter().all(|a| !a.has_in() && !a.has_out() && corner(a.p)) +} + +/// Replace the objects with this kind of issue (the outermost ones each round, until none is +/// left) by what [`Kind::replacement`] gives. +fn restructure(d: &mut Document, scope: &mut Scope, kind: Kind) -> Result { + let mut out = Outcome::default(); + for _ in 0..MAX_PASSES { + let found: Vec<(NodeId, Vec)> = { + let d: &Document = d; + let cx = Context { d, symbols: d.symbol_boxes() }; + let all: Vec<(NodeId, Vec)> = + objects(d, scope).into_iter().filter_map(|(n, pl)| Some((n.id, kind.replacement(&cx, n, pl)?))).collect(); + let keep: HashSet = outermost(d, all.iter().map(|(id, _)| *id).collect()).into_iter().collect(); + all.into_iter().filter(|(id, _)| keep.contains(id)).collect() + }; + if found.is_empty() { + break; + } + if let Scope::Objects(roots) = scope { + for (id, nodes) in &found { + if let Some(at) = roots.iter().position(|r| r == id) { + roots.splice(at..=at, nodes.iter().map(|n| n.id)); + } + } + } + out.ids.extend(found.iter().map(|(id, _)| *id)); + d.insert_beside(found, true)?; + } + out.count = out.ids.len(); + Ok(out) +} + +/// Run `f` on a copy of each path in scope (not guides), and keep the copies it changed: `f` +/// returns how many issues it fixed. +fn reshape(d: &mut Document, scope: &Scope, f: impl Fn(&Node, &mut PathData) -> usize) -> Result { + let changed: Vec<(NodeId, PathData, usize)> = objects(d, scope) + .into_iter() + .filter_map(|(n, _)| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return None }; + let mut p = path.clone(); + let k = f(n, &mut p); + (k > 0).then_some((n.id, p, k)) + }) + .collect(); + let mut out = Outcome::default(); + for (id, p, k) in changed { + set_path(d, id, p); + out.count += k; + out.ids.push(id); + } + Ok(out) +} + +/// Give path `id` the geometry `p` (it stops being a live shape). +pub(super) fn set_path(d: &mut Document, id: NodeId, p: PathData) { + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = p; + *live = None; + } +} + +/// Filled Open Paths: close the open subpaths of a path with a fill and no stroke. +fn close_filled(n: &Node, p: &mut PathData) -> usize { + let items = &n.appearance.items; + let filled = items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none())); + let stroked = items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0)); + if !filled || stroked { + return 0; + } + let mut count = 0; + for sp in p.subpaths.iter_mut().filter(|sp| !sp.closed && sp.anchors.len() >= 2) { + sp.closed = true; + count += 1; + } + count +} + +/// Nearly Coincident Anchors: anchors of the paths in scope within [`NEAR`] of one another (but +/// not neighbours on one path, which Duplicate Anchors merges) move onto the first of them. +fn near_points(d: &mut Document, scope: &Scope) -> Result { + // Each anchor: (path, subpath, anchor, its subpath's length and closedness). + let mut refs: Vec<(NodeId, usize, usize, usize, bool)> = vec![]; + let mut points: Vec = vec![]; + for (n, _) in objects(d, scope) { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { continue }; + for (si, sp) in path.subpaths.iter().enumerate() { + for (ai, a) in sp.anchors.iter().enumerate().take(MAX_ANCHORS.saturating_sub(points.len())) { + refs.push((n.id, si, ai, sp.anchors.len(), sp.closed)); + points.push(a.p); + } + } + } + let neighbours = |i: usize, j: usize| { + let (Some(a), Some(b)) = (refs.get(i), refs.get(j)) else { return false }; + let gap = a.2.abs_diff(b.2); + a.0 == b.0 && a.1 == b.1 && (gap == 1 || (a.4 && gap + 1 == a.3)) + }; + let mut moves: HashMap> = HashMap::new(); + let mut count = 0; + for group in po::near_point_groups(&points, NEAR, neighbours) { + let Some(&to) = group.first().and_then(|&i| points.get(i)) else { continue }; + for &i in &group { + if let (Some(&(id, si, ai, ..)), Some(&p)) = (refs.get(i), points.get(i)) + && p != to + { + moves.entry(id).or_default().push((si, ai, to)); + count += 1; + } + } + } + let mut ids: Vec = moves.keys().copied().collect(); + ids.sort_unstable(); + for id in &ids { + let Some(mut p) = d.node(*id).and_then(Node::path_data).cloned() else { continue }; + for &(si, ai, to) in moves.get(id).into_iter().flatten() { + if let Some(a) = p.anchor_mut(si, ai) { + a.translate(to - a.p); + } + } + set_path(d, *id, p); + } + Ok(Outcome { count, ids, artboards: vec![] }) +} + +/// Empty Artboards: the artboards with no art on them (as Delete Empty Artboards finds them), +/// deleted with their guides. Only a check of the whole document looks at artboards. +fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result { + let Scope::Document = scope else { return Ok(Outcome::default()) }; + let empty = empty_artboards(d); + // The last first, so the others keep their places. + for &i in empty.iter().rev() { + if i < d.artboards.len() { + let id = d.artboards.remove(i).id; + d.retire_artboard_id(id); + d.retain_guides(sel, |_, g| g.artboard != Some(id)); + } + } + Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty }) +} diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs new file mode 100644 index 0000000000..d02e1e4c09 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -0,0 +1,356 @@ +//! Artwork Cleanup's commands: Simplify Anchors (Keep Shape), the health check's kinds found and +//! fixed one by one, Fix as one undo step, scopes, Show, Deep Ungroup and Rejoin Path Pieces. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; +use vectorcraft_geom::{FillRule, Rect}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +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()) +} + +/// A path through `pts` (anchors as `{x, y, out?}` objects). +fn path(s: &mut Session, anchors: Value, closed: bool) -> NodeId { + id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()) +} + +fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId { + path(s, pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(), false) +} + +fn node(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).cloned() +} + +fn change(s: &mut Session, id: NodeId, f: impl FnOnce(&mut Node)) { + s.edit("t", |d, _| { + f(d.node_mut(id).unwrap()); + Ok(()) + }) + .unwrap(); +} + +/// Put `id` inside a new container that `kind` makes of its members. +fn wrap(s: &mut Session, id: NodeId, kind: fn(Vec>) -> NodeKind) -> NodeId { + s.edit("t", |d, _| { + let w = d.alloc_id(); + Ok(d.wrap(&[id], |c| Node::new(w, kind(c)))?) + }) + .unwrap() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn anchors(s: &Session, id: NodeId) -> usize { + node(s, id).unwrap().path_data().unwrap().anchor_count() +} + +/// How many issues of `kind` a check of `scope` finds. +fn found(s: &mut Session, kind: &str, scope: &str) -> usize { + let r = s.execute("addon.cleanup.check", &json!({"kinds": [kind], "scope": scope})).unwrap(); + r["findings"].as_array().unwrap().iter().find(|f| f["kind"] == kind).map_or(0, |f| f["count"].as_u64().unwrap() as usize) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn simplify_keeps_the_shape_with_fewer_anchors_in_one_step() { + let mut s = session(); + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(anchors(&s, e), 16); + let bounds = node(&s, e).unwrap().geometric_bounds().unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(16), Some(anchors(&s, e) as u64))); + assert!(anchors(&s, e) <= 8, "{r}"); + let now = node(&s, e).unwrap().geometric_bounds().unwrap(); + for (a, b) in [(bounds.x0, now.x0), (bounds.y0, now.y0), (bounds.x1, now.x1), (bounds.y1, now.y1)] { + assert!((a - b).abs() < 0.4, "{bounds:?} → {now:?}"); + } + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, e), 16); + // A rectangle's corners stay; the anchors on its sides go. + let r = rect(&mut s, 200.0, 50.0, 100.0, 60.0); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(anchors(&s, r), 8); + s.execute("addon.cleanup.simplify", &json!({"protectCorners": true})).unwrap(); + assert_eq!(anchors(&s, r), 4); + // Nothing left to remove: no undo step. + let steps = undo_steps(&s); + s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + for bad in [json!({"tolerance": 0}), json!({"tolerance": 101}), json!({"tolerance": "20"}), json!({"protectCorners": 1})] { + assert!(s.execute("addon.cleanup.simplify", &bad).is_err(), "{bad}"); + } +} + +/// Each kind: what makes the issue in a fresh document (beside a clean rectangle). +fn make_issue(s: &mut Session, kind: &str) { + match kind { + "emptyText" => { + s.execute("text.create", &json!({"x": 20, "y": 20, "text": " "})).unwrap(); + } + "strayPoints" => { + path(s, json!([{"x": 30, "y": 30}]), false); + } + "unpainted" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + change(s, id, |n| n.appearance = Appearance::default().into()); + } + "zeroOpacity" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + change(s, id, |n| n.opacity = 0.0); + } + "duplicateObjects" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + s.edit("t", |d, _| { + let mut copy = d.node(id).unwrap().clone(); + copy.id = d.alloc_id(); + let (parent, i, _) = d.position(id).unwrap(); + Ok(d.insert(parent, i + 1, copy)?) + }) + .unwrap(); + } + "offArtboard" => { + rect(s, -500.0, -500.0, 30.0, 30.0); + } + "duplicateAnchors" => { + line(s, &[(10.0, 150.0), (50.0, 150.0), (50.005, 150.0), (50.0, 190.0)]); + } + "tinyHandles" => { + path(s, json!([{"x": 10, "y": 150, "out": [10.004, 150]}, {"x": 60, "y": 190}]), false); + } + "collinearAnchors" => { + line(s, &[(10.0, 150.0), (30.0, 150.0), (50.0, 150.0), (50.0, 190.0)]); + } + "nearPoints" => { + line(s, &[(10.0, 150.0), (50.0, 150.0)]); + line(s, &[(50.005, 150.0), (90.0, 190.0)]); + } + "nearlyClosed" => { + line(s, &[(10.0, 150.0), (50.0, 150.0), (50.0, 190.0), (10.005, 150.0)]); + } + "filledOpenPaths" => { + let id = line(s, &[(10.0, 150.0), (50.0, 150.0), (50.0, 190.0)]); + change(s, id, |n| n.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0).into()); + } + "needlessClipGroups" => { + let inner = rect(s, 30.0, 160.0, 20.0, 20.0); + let clip = rect(s, 20.0, 150.0, 50.0, 50.0); + select(s, &[inner, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + } + "needlessCompounds" => { + // A compound path holds the paint of its paths. + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + let look = node(s, id).unwrap().appearance; + let compound = wrap(s, id, |children| NodeKind::Compound { children, rule: FillRule::NonZero }); + change(s, compound, |n| n.appearance = look); + } + "needlessGroups" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + wrap(s, id, |children| NodeKind::Group { children, clip: false }); + } + "emptyArtboards" => { + s.edit("t", |d, _| { + let mut a = d.artboards[0].clone(); + a.id = d.next_artboard_id(); + a.rect = Rect::new(1000.0, 1000.0, 1100.0, 1100.0); + d.artboards.push(a); + Ok(()) + }) + .unwrap(); + } + _ => panic!("no setup for {kind}"), + } +} + +const KINDS: [&str; 16] = [ + "emptyText", + "strayPoints", + "unpainted", + "zeroOpacity", + "duplicateObjects", + "offArtboard", + "duplicateAnchors", + "tinyHandles", + "collinearAnchors", + "nearPoints", + "nearlyClosed", + "filledOpenPaths", + "needlessClipGroups", + "needlessCompounds", + "needlessGroups", + "emptyArtboards", +]; + +#[test] +fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() { + let mut clean = session(); + let r = rect(&mut clean, 200.0, 20.0, 80.0, 60.0); + let before = node(&clean, r).unwrap(); + assert_eq!(clean.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0, "clean art has no issues"); + assert_eq!(clean.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + assert_eq!(node(&clean, r).unwrap(), before); + for kind in KINDS { + let mut s = session(); + let r = rect(&mut s, 200.0, 20.0, 80.0, 60.0); + make_issue(&mut s, kind); + select(&mut s, &[]); + assert!(found(&mut s, kind, "document") > 0, "{kind} not found"); + let fixed = s.execute("addon.cleanup.fix", &json!({"kinds": [kind], "scope": "document"})).unwrap(); + assert!(fixed["fixed"][kind].as_u64().unwrap() > 0, "{kind}: {fixed}"); + assert_eq!(found(&mut s, kind, "document"), 0, "{kind} still found after Fix"); + assert_eq!(s.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0, "{kind} left other issues"); + assert_eq!(node(&s, r).unwrap(), before, "{kind} changed the clean rectangle"); + } +} + +/// Type set twice in the same place (from a PDF, or for a fake bold) is a duplicate within a point: +/// Show selects the upper copy and Fix removes it. Other text, or the same text further off, stays. +#[test] +fn doubled_type_within_a_point_is_a_duplicate() { + let mut s = session(); + let text = |s: &mut Session, x: f64, text: &str| id_of(&s.execute("text.create", &json!({"x": x, "y": 100, "text": text})).unwrap()); + let base = text(&mut s, 20.0, "Total"); + let doubled = text(&mut s, 20.4, "Total"); + let other = text(&mut s, 20.0, "Subtotal"); + let far = text(&mut s, 23.0, "Subtotal"); + assert_eq!(found(&mut s, "duplicateObjects", "document"), 1); + let shown = s.execute("addon.cleanup.show", &json!({"kind": "duplicateObjects", "scope": "document"})).unwrap(); + assert_eq!(shown["ids"], json!([doubled.0])); + s.execute("addon.cleanup.fix", &json!({"kinds": ["duplicateObjects"], "scope": "document"})).unwrap(); + assert!(node(&s, doubled).is_none()); + for id in [base, other, far] { + assert!(node(&s, id).is_some(), "{id:?} stays"); + } +} + +#[test] +fn fix_all_is_one_undo_step() { + let mut s = session(); + for kind in KINDS { + make_issue(&mut s, kind); + } + select(&mut s, &[]); + let total = s.execute("addon.cleanup.check", &json!({})).unwrap()["total"].as_u64().unwrap(); + assert!(total >= 16, "{total}"); + let (steps, doc) = (undo_steps(&s), s.doc().unwrap().doc.clone()); + let r = s.execute("addon.cleanup.fix", &json!({})).unwrap(); + assert_eq!(r["scope"], "document"); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, doc.layers); + assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len()); +} + +#[test] +fn the_scope_is_the_selection_or_the_document() { + let mut s = session(); + let a = path(&mut s, json!([{"x": 30, "y": 30}]), false); + let b = path(&mut s, json!([{"x": 60, "y": 30}]), false); + select(&mut s, &[a]); + let r = s.execute("addon.cleanup.check", &json!({"kinds": ["strayPoints"]})).unwrap(); + assert_eq!((r["scope"].as_str(), r["total"].as_u64()), (Some("selection"), Some(1))); + assert_eq!(found(&mut s, "strayPoints", "document"), 2); + s.execute("addon.cleanup.fix", &json!({"kinds": ["strayPoints"]})).unwrap(); + assert!(node(&s, a).is_none() && node(&s, b).is_some(), "only the selection is fixed"); + // Nothing selected: the document. + let r = s.execute("addon.cleanup.check", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["total"].as_u64()), (Some("document"), Some(1))); + assert!(s.execute("addon.cleanup.check", &json!({"scope": "selection"})).is_err(), "nothing selected"); + for bad in [json!({"scope": "page"}), json!({"kinds": ["nope"]}), json!({"kinds": "strayPoints"}), json!({"kinds": [1]})] { + assert!(s.execute("addon.cleanup.check", &bad).is_err(), "{bad}"); + assert!(s.execute("addon.cleanup.fix", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn show_selects_the_objects_with_the_issue() { + let mut s = session(); + rect(&mut s, 200.0, 20.0, 80.0, 60.0); + let stray = path(&mut s, json!([{"x": 30, "y": 30}]), false); + select(&mut s, &[]); + let r = s.execute("addon.cleanup.show", &json!({"kind": "strayPoints"})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [stray]); + assert!(s.execute("addon.cleanup.show", &json!({"kind": "emptyText", "scope": "document"})).is_err(), "no such issue"); + assert!(s.execute("addon.cleanup.show", &json!({})).is_err() && s.execute("addon.cleanup.show", &json!({"kind": "x"})).is_err()); +} + +#[test] +fn deep_ungroup_takes_apart_every_level_but_clipping_groups() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + select(&mut s, &[b, c]); + let inner = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, inner, |n| n.opacity = 0.5); + let clipped = rect(&mut s, 100.0, 10.0, 10.0, 10.0); + let clip = rect(&mut s, 95.0, 5.0, 30.0, 30.0); + select(&mut s, &[clipped, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip_group = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[a, inner, clip_group]); + let outer = id_of(&s.execute("object.group", &json!({})).unwrap()); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap(); + assert_eq!(r["ungrouped"], 2); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.doc().unwrap().doc; + let layer: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [a, b, c, clip_group]); + assert!(d.node(outer).is_none() && d.node(inner).is_none()); + assert_eq!(d.node(b).unwrap().opacity, 0.5, "members keep their groups' opacity"); + assert_eq!(s.doc().unwrap().selection.objects.len(), 4); + // Asked to, clipping groups come apart too, their clipping paths kept as plain paths. + select(&mut s, &[clip_group]); + s.execute("addon.cleanup.deepUngroup", &json!({"includeClipGroups": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(clip_group).is_none()); + assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Path { clipping: false, .. })); +} + +#[test] +fn rejoin_joins_pieces_within_the_gap_only() { + let mut s = session(); + let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]); + let b = line(&mut s, &[(50.05, 10.0), (90.0, 50.0)]); + let far = line(&mut s, &[(92.0, 50.0), (120.0, 50.0)]); + select(&mut s, &[a, b, far]); + let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap(); + assert_eq!((r["joined"].as_u64(), r["removed"].as_u64()), (Some(1), Some(1))); + // The topmost piece takes the joined path. + assert!(node(&s, a).is_none()); + assert_eq!(anchors(&s, b), 3); + assert_eq!(anchors(&s, far), 2, "beyond the gap"); + select(&mut s, &[b, far]); + let r = s.execute("addon.cleanup.rejoin", &json!({"gap": 3})).unwrap(); + assert_eq!(r["joined"], 1); + assert_eq!(anchors(&s, far), 4); + for bad in [json!({"gap": -1}), json!({"gap": 7}), json!({"gap": "1"})] { + assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}"); + } +} diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs new file mode 100644 index 0000000000..dd7cb67888 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -0,0 +1,953 @@ +//! Artwork Cleanup's text tools: Break Text into Lines / Paragraphs / Words / Glyphs, Combine Point +//! Text, Join Point Text, Split Text at Cursor, Remove Line / Paragraph Breaks, Set Alignment, Keep Position, Reset +//! Text Transform and Replace Missing Fonts. Each is one undo step. Pieces keep their characters' +//! styles and stay where the layout drew them: each is moved so the glyph of its first character +//! lands where it was. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, ParaStyle, RubySpan, TextKind, TextObject}; +use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit}; + +use crate::cmd::textedit::editing_range; +use crate::cmd::typecmd::refresh_bounds; +use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// Most text objects one command takes. +const MAX_TEXTS: usize = 10_000; +/// Most pieces Break Text and Split Text at Cursor make at once. +const MAX_PIECES: usize = 20_000; +/// Most breaks Remove Line / Paragraph Breaks removes at once. +const MAX_BREAKS: usize = 200_000; +/// Most pieces Combine Point Text tries to join, counted over every try: past it, what it joined +/// so far is the result. +const MAX_JOIN_TRIES: usize = 200_000; +/// How far (pt) a glyph Combine Point Text sets may land from where it was. +const TOLERANCE: f64 = 0.01; +/// Combine Point Text: pieces whose baselines are within this many ems of each other share a line +/// (the difference becomes baseline shift); a gap wider than `MAX_GAP` ems, or an overlap of more +/// than `MAX_OVERLAP`, starts another object. +const SAME_LINE: f64 = 0.4; +const MAX_GAP: f64 = 10.0; +const MAX_OVERLAP: f64 = 1.0; +/// Tracking Combine Point Text may give a character (thousandths of an em). +const TRACKING: std::ops::RangeInclusive = -1000.0..=10000.0; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.cleanup.breakText", + "Break Text", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}", + has_selection, + break_text + ), + cmd!( + "addon.cleanup.combineText", + "Combine Point Text", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{ids?: [id…] (default: the selection)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}", + has_selection, + combine_text + ), + cmd!( + "addon.cleanup.joinText", + "Join Point Text", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{ids?: [id…] (default: the selection)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}", + has_selection, + join_text + ), + cmd!( + "addon.cleanup.removeBreaks", + "Remove Breaks", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool, else in all the text of the selected type, as one undo step; a break between two words becomes a space → {ids, removed}", + has_selection, + remove_breaks + ), + cmd!( + "addon.cleanup.splitText", + "Split Text at Cursor", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{} while a Type tool edits horizontal point or area type: the text before the selected characters, they and the text after become point type objects of their own (at a cursor: before and after it), each where its characters were, as one undo step; spaces at the ends of each piece go, and editing ends with the pieces selected → {ids}", + editing_text, + split_text + ), + cmd!( + "addon.cleanup.alignInPlace", + "Set Alignment, Keep Position", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}", + has_selection, + align_in_place + ), + cmd!( + "addon.cleanup.resetTextTransform", + "Reset Text Transform", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}", + has_selection, + reset_transform + ), + cmd!( + "addon.cleanup.replaceFonts", + "Replace Missing Fonts…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}", + has_doc, + replace_fonts + ), + ] +} + +/// Enabled while a Type tool edits text. +fn editing_text(s: &Session) -> std::result::Result<(), String> { + match s.tool_options().get("editing") { + Some(v) if !v.is_null() => Ok(()), + _ => Err("Click in type with a Type tool to split it".into()), + } +} + +/// The type objects under `roots` (inside groups and layers, not live art) that can be edited. +fn texts_under(d: &Document, roots: &[NodeId]) -> Result> { + fn visit(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Text(_) => out.push(n.id), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)), + _ => {} + } + } + let mut out = vec![]; + roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); + let editable = d.editable(); + out.retain(|id| editable(*id)); + out.dedup(); + if out.len() > MAX_TEXTS { + return Err(EngineError::Other("Too many type objects to change at once".into())); + } + Ok(out) +} + +fn text_of(d: &Document, id: NodeId) -> Option<&TextObject> { + match &d.node(id)?.kind { + NodeKind::Text(t) => Some(t), + _ => None, + } +} + +fn layout(t: &TextObject) -> TextLayout { + vectorcraft_text::layout(FontDb::global(), t) +} + +/// Where the layout draws the character at `byte` (the one it starts in): its glyph's pen position. +fn glyph_at(lay: &TextLayout, byte: usize) -> Option { + let start = lay.glyphs.iter().filter(|g| g.len > 0 && g.byte <= byte).map(|g| g.byte).max()?; + lay.glyphs.iter().find(|g| g.len > 0 && g.byte == start).map(|g| g.origin) +} + +/// The pen position of the glyph that starts at `byte`, if one does. +fn glyph_starting(lay: &TextLayout, byte: usize) -> Option { + lay.glyphs.iter().find(|g| g.len > 0 && g.byte == byte).map(|g| g.origin) +} + +/// The first glyph of line `l`, in text order. +fn line_start(lay: &TextLayout, l: usize) -> Option { + let line = lay.lines.get(l)?; + let g = lay.glyphs.get(line.glyph_start..line.glyph_end)?.iter().filter(|g| g.len > 0).min_by_key(|g| g.byte)?; + Some(g.origin) +} + +/// `a..b` of `text` without the white space at its ends; None when nothing else is left. +fn trimmed(text: &str, a: usize, b: usize) -> Option<(usize, usize)> { + let s = text.get(a..b)?; + let start = a + (s.len() - s.trim_start().len()); + let end = a + s.trim_end().len(); + (start < end).then_some((start, end)) +} + +/// Paragraph alignment as point type keeps it: justified lines align to their side. +fn point_justify(j: Justify) -> Justify { + match j { + Justify::JustifyLeft | Justify::JustifyAll => Justify::Left, + Justify::JustifyCenter => Justify::Center, + Justify::JustifyRight => Justify::Right, + j => j, + } +} + +#[derive(Clone, Copy, PartialEq)] +enum By { + Lines, + Paragraphs, + Words, + Glyphs, +} + +/// A type object being cut into point type pieces: its text as drawn (Shrink Text to Fit's sizes +/// taken in) and its layout. +struct Source { + t: TextObject, + lay: TextLayout, + text: String, +} + +impl Source { + /// Horizontal point or area type that isn't threaded and whose text all fits; None otherwise. + fn of(d: &Document, id: NodeId) -> Option { + let t = text_of(d, id)?; + if t.vertical || matches!(t.kind, TextKind::OnPath { .. }) || d.text_threads.iter().any(|th| th.contains(&id)) { + return None; + } + let lay = layout(t); + // Text left out of a frame would be lost with it. + if lay.overflow { + return None; + } + let t = if (lay.fit_scale - 1.0).abs() > 1e-9 { vectorcraft_text::scaled(t, lay.fit_scale) } else { t.clone() }; + Some(Self { text: t.plain_text(), t, lay }) + } + + /// The byte ranges of the pieces `by` cuts the text into. + fn ranges(&self, by: By) -> Vec<(usize, usize)> { + let text = &self.text; + match by { + By::Paragraphs => { + let mut out = vec![]; + let mut a = 0; + for (i, _) in text.match_indices('\n') { + out.push((a, i)); + a = i + 1; + } + out.push((a, text.len())); + out + } + By::Lines => self.lay.lines.iter().map(|l| (l.start, l.end)).collect(), + By::Words => { + let mut out = vec![]; + for l in &self.lay.lines { + let Some(s) = text.get(l.start..l.end) else { continue }; + let mut word: Option = None; + for (i, c) in s.char_indices() { + match (c.is_whitespace(), word) { + (true, Some(w)) => { + out.push((l.start + w, l.start + i)); + word = None; + } + (false, None) => word = Some(i), + _ => {} + } + } + if let Some(w) = word { + out.push((l.start + w, l.end)); + } + } + out + } + By::Glyphs => { + // One piece per cluster (a ligature's characters stay together). + let mut clusters = std::collections::BTreeMap::new(); + for g in self.lay.glyphs.iter().filter(|g| g.len > 0) { + let end = clusters.entry(g.byte).or_insert(g.byte + g.len); + *end = (*end).max(g.byte + g.len); + } + clusters.into_iter().collect() + } + } + } + + /// Point type holding bytes `a..b` (white space at its ends left out) where they were drawn. + /// Lines the layout wrapped end in a forced line break; `lists` keeps bulleted paragraphs' + /// bullets where the piece starts its paragraph. + fn piece(&self, (a, b): (usize, usize), lists: bool) -> Option { + let (a, b) = trimmed(&self.text, a, b)?; + let mut p = TextObject::point(Point::ZERO, "", CharStyle::default()); + p.runs = edit::slice_runs(&self.t.runs, a, b); + p.xf = self.t.xf; + p.optical_margin = self.t.optical_margin; + p.system_layout = self.t.system_layout; + p.fractional_widths = self.t.fractional_widths; + p.ruby = + self.t.ruby.iter().filter(|r| a <= r.start && r.end <= b).map(|r| RubySpan { start: r.start - a, end: r.end - a, ..r.clone() }).collect(); + // The paragraphs it holds, with their styles; the first keeps its bullet only from its start. + let starts_para = self.text.get(..a).is_some_and(|s| s.rsplit('\n').next().is_some_and(|line| line.trim().is_empty())); + let styles = self.t.paragraph_styles(); + let mut paras: Vec = styles.get(self.t.paragraphs_in(a, b))?.to_vec(); + for (i, para) in paras.iter_mut().enumerate() { + para.justify = point_justify(para.justify); + if !(lists && (i > 0 || starts_para) && para.list.as_ref().is_some_and(|l| l.number.is_none())) { + para.list = None; + } + } + p.set_paragraph_styles(paras); + // Lines the layout wrapped end in a forced line break, in place of the spaces they ended in. + let mut wraps = vec![]; + for next in self.lay.lines.iter().skip(1).filter(|l| a < l.start && l.start < b) { + let content = self.text.get(..next.start)?.trim_end_matches([' ', '\t']); + // A line that ends in a break of its own keeps it. + if !content.ends_with(['\n', '\u{2028}']) { + wraps.push((content.len().max(a) - a, next.start - a)); + } + } + for &(s, e) in wraps.iter().rev() { + edit::replace_range(&mut p.runs, s, e, "\u{2028}"); + p.ruby_after_replace(s, e, '\u{2028}'.len_utf8()); + } + self.place(&mut p, a)?; + Some(p) + } + + /// Move `p` (cut from byte `a`) so the glyph of its first character lands where it was drawn. + /// A piece of several lines that starts inside a left-aligned line takes a first-line indent, + /// so its later lines stay where they were too. + fn place(&self, p: &mut TextObject, a: usize) -> Option<()> { + let lay = layout(p); + let mut shift: Vec2 = glyph_at(&self.lay, a)? - glyph_at(&lay, 0)?; + let first = self.lay.lines.iter().rposition(|l| l.start <= a); + if let (Some(now), Some(was)) = (line_start(&lay, 1), first.and_then(|l| line_start(&self.lay, l + 1))) { + let off = was.x - (now.x + shift.x); + let left = match p.para.justify { + Justify::Left => true, + Justify::Auto => lay.lines.first().is_some_and(|l| !l.rtl), + _ => false, + }; + if left && off.abs() > 1e-6 { + p.edit_paras(Some(0..1), |para| para.first_line_indent -= off); + shift.x += off; + } + } + p.xf = self.t.xf * Affine::translate(shift); + Some(()) + } +} + +/// Put each object of `items` (id, the node, its pieces) out of the document, its pieces in its +/// place, as one undo step labelled `label`, the pieces selected → their ids. +fn replace_with_pieces(s: &mut Session, label: &str, items: Vec<(NodeId, Node, Vec)>) -> Result> { + s.edit(label, |d, sel| { + let (mut made, mut places) = (vec![], vec![]); + for (id, mut node, pieces) in items { + // A light template: the pieces take its paint and attributes, not its text. + node.kind = NodeKind::Text(Box::new(TextObject::point(Point::ZERO, "", CharStyle::default()))); + let nodes: Vec = pieces + .into_iter() + .map(|mut t| { + refresh_bounds(&mut t); + let mut n = d.reid(&node); + n.kind = NodeKind::Text(Box::new(t)); + n + }) + .collect(); + made.extend(nodes.iter().map(|n| n.id)); + places.push((id, nodes)); + } + d.insert_beside(places, true)?; + sel.set(made.iter().copied()); + Ok(made.iter().map(|i| i.0).collect()) + }) +} + +fn ids_json(ids: &[NodeId]) -> Vec { + ids.iter().map(|i| i.0).collect() +} + +fn break_text(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.breakText"; + let by = match text_param(p, "by", C)?.unwrap_or("lines") { + "lines" => By::Lines, + "paragraphs" => By::Paragraphs, + "words" => By::Words, + "glyphs" => By::Glyphs, + other => return Err(bad(C, format!("`by` must be lines, paragraphs, words or glyphs, not {other:?}"))), + }; + let d = &s.doc()?.doc; + let (mut items, mut skipped, mut count) = (vec![], vec![], 0); + for id in texts_under(d, &checked_ids_or_selection(s, p, C)?)? { + let (Some(src), Some(node)) = (Source::of(d, id), d.node(id)) else { + skipped.push(id); + continue; + }; + let ranges = src.ranges(by); + count += ranges.len(); + if count > MAX_PIECES { + return Err(EngineError::Other("Too many pieces to make at once".into())); + } + let pieces: Vec = ranges.into_iter().filter_map(|r| src.piece(r, by == By::Paragraphs)).collect(); + if pieces.is_empty() { + skipped.push(id); + } else { + items.push((id, node.clone(), pieces)); + } + } + if items.is_empty() { + return Err(EngineError::Other("Select horizontal point or area type whose text fits".into())); + } + let ids = replace_with_pieces(s, "Break Text", items)?; + Ok(json!({ "ids": ids, "skipped": ids_json(&skipped) })) +} + +fn split_text(s: &mut Session, _: &Value) -> Result { + let Some((id, a, b)) = editing_range(s)? else { + return Err(EngineError::Other("Click in type with a Type tool to split it".into())); + }; + let d = &s.doc()?.doc; + let (Some(src), Some(node)) = (Source::of(d, id), d.node(id).filter(|_| d.is_editable(id))) else { + return Err(EngineError::Other("Select horizontal point or area type whose text fits".into())); + }; + let text = &src.text; + let (a, b) = (edit::floor_char(text, a.min(b)), edit::floor_char(text, a.max(b))); + let cuts: Vec<(usize, usize)> = if a == b { vec![(0, a), (a, text.len())] } else { vec![(0, a), (a, b), (b, text.len())] }; + let pieces: Vec = cuts.into_iter().filter_map(|r| src.piece(r, true)).collect(); + if pieces.len() < 2 { + return Err(EngineError::Other("Nothing to split at the cursor".into())); + } + let node = node.clone(); + let ids = replace_with_pieces(s, "Split Text at Cursor", vec![(id, node, pieces)])?; + // The text edited is gone: the pieces stay selected. + s.set_tool_option("stopEditing", &Value::Bool(true)); + Ok(json!({ "ids": ids })) +} + +/// One piece of point type Combine Point Text takes: its text with its object's scale taken into +/// its characters, and where it starts and ends along its line in the frame of its turn and shear. +struct Piece { + id: NodeId, + t: TextObject, + /// The object's turn and shear (`xf` without its move). + turn: [f64; 4], + /// Where its first character's glyph starts on its baseline, in that frame. + at: Point, + /// Where its last glyph ends along the line, in that frame. + end: f64, + /// Its first character's size. + size: f64, + /// Each character's pen position from the first's (byte, x), as it lays out alone. + pens: Vec<(usize, f64)>, +} + +impl Piece { + fn of(d: &Document, id: NodeId) -> Option<(Self, &Node)> { + let node = d.node(id)?; + let NodeKind::Text(t) = &node.kind else { return None }; + let text = t.plain_text(); + if t.vertical || !matches!(t.kind, TextKind::Point) || text.trim().is_empty() || text.contains(['\n', '\u{2028}']) { + return None; + } + let mut t = (**t).clone(); + t.scale_text_attributes(); + t.style_scale()?; + let lay = layout(&t); + let line = lay.lines.first().filter(|l| !l.rtl && lay.lines.len() == 1)?; + let first = glyph_at(&lay, 0)?; + // The first glyph of each cluster (a mark drawn over it shares its byte). + let mut seen = std::collections::HashSet::new(); + let pens = lay.glyphs.iter().filter(|g| g.len > 0 && seen.insert(g.byte)).map(|g| (g.byte, g.origin.x - first.x)).collect(); + let end = lay.glyphs.iter().map(|g| g.origin.x + g.advance).fold(first.x, f64::max) - first.x; + let [a, b, c, dd, _, _] = t.xf.as_coeffs(); + let turn = Affine::new([a, b, c, dd, 0.0, 0.0]); + let at = turn.inverse() * (t.xf * Point::new(first.x, line.baseline)); + let size = t.runs.first()?.style.size; + if !(at.x.is_finite() && at.y.is_finite() && size > 0.0) { + return None; + } + Some((Self { id, t, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node)) + } + + /// Whether `o` is turned and sheared alike. + fn turned_like(&self, o: &Piece) -> bool { + self.turn.iter().zip(&o.turn).all(|(x, y)| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0)) + } +} + +/// Whether two objects look alike apart from their text (paint, opacity, blending, effects). +fn same_look(a: &Node, b: &Node) -> bool { + a.appearance == b.appearance + && a.opacity == b.opacity + && a.blend == b.blend + && a.isolate == b.isolate + && a.knockout == b.knockout + && a.extras == b.extras +} + +/// How wide a space of `style` is. +fn space_width(style: &CharStyle) -> f64 { + let probe = TextObject::point(Point::ZERO, " ", CharStyle { tracking: 0.0, ..style.clone() }); + layout(&probe).glyphs.first().map_or(style.size * 0.25, |g| g.advance) +} + +/// `chain` (pieces left to right on one line) as one point type object whose glyphs land where +/// theirs were, or the index of the first piece that can't join the ones before it so. +fn merge(chain: &[&Piece]) -> std::result::Result { + let Some(first) = chain.first() else { return Err(0) }; + let mut runs = vec![]; + // Each piece's first byte, and the byte range of the character before it (whose tracking sets + // the gap). + let (mut starts, mut before) = (vec![], vec![]); + let mut text = String::new(); + for (k, p) in chain.iter().enumerate() { + if let Some(prev) = k.checked_sub(1).and_then(|i| chain.get(i)) { + let starts_blank = p.t.plain_text().starts_with(char::is_whitespace); + let last = prev.t.runs.iter().rev().find(|r| !r.text.is_empty()).map(|r| r.style.clone()).unwrap_or_default(); + if !text.ends_with(char::is_whitespace) && !starts_blank && p.at.x - prev.end >= 0.5 * space_width(&last) { + runs.push(vectorcraft_doc::TextRun::new(" ", last)); + text.push(' '); + } + let c = text.chars().next_back().map_or(1, char::len_utf8); + before.push((text.len() - c, text.len())); + } + starts.push(text.len()); + // Baselines a little apart: the difference is baseline shift (up is positive). + let shift = first.at.y - p.at.y; + for r in &p.t.runs { + let mut r = r.clone(); + r.style.baseline_shift += shift; + text.push_str(&r.text); + runs.push(r); + } + } + let mut m = first.t.clone(); + m.set_all_paras(ParaStyle { justify: Justify::Left, ..first.t.para.clone() }); + let [a, b, c, d] = first.turn; + let base = Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate(first.at.to_vec2()); + m.xf = base; + m.runs = runs; + m.ruby.clear(); + // Tracking after the character before each piece, until each lands where it was. + let targets: Vec = chain.iter().map(|p| p.at.x - first.at.x).collect(); + let mut lay = layout(&m); + for _ in 0..4 { + // A piece whose first character joins the one before it (a ligature) can't keep its place. + let xs: Vec = match starts.iter().enumerate().map(|(k, b)| glyph_starting(&lay, *b).map(|g| g.x).ok_or(k)).collect() { + Ok(xs) => xs, + Err(k) => return Err(k.max(1)), + }; + let x0 = xs.first().copied().unwrap_or(0.0); + let off: Vec = targets.iter().zip(&xs).map(|(t, x)| t - (x - x0)).collect(); + if off.iter().all(|o| o.abs() <= TOLERANCE * 0.5) { + break; + } + // Moving piece k moves those after it as far. + for (k, w) in off.windows(2).enumerate() { + let (delta, Some(&(s, e))) = (w[1] - w[0], before.get(k)) else { continue }; + if delta.abs() > 1e-9 { + edit::style_range(&mut m.runs, s, e, |st| st.tracking += delta / st.size.max(1e-6) * 1000.0); + if !TRACKING.contains(&edit::style_at(&m.runs, s).tracking) { + return Err(k + 1); + } + } + } + lay = layout(&m); + } + // Every glyph where it was, within the tolerance; else the run ends before the piece that moved. + let x0 = glyph_starting(&lay, 0).map_or(0.0, |g| g.x); + for (k, p) in chain.iter().enumerate() { + let (Some(&start), Some(&target)) = (starts.get(k), targets.get(k)) else { return Err(k.max(1)) }; + let moved = p.pens.iter().any(|(byte, x)| glyph_starting(&lay, start + byte).is_none_or(|g| (g.x - x0 - target - x).abs() > TOLERANCE)); + if moved { + return Err(k.max(1)); + } + } + m.xf = base * Affine::translate((-x0, 0.0)); + Ok(m) +} + +fn combine_text(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.combineText"; + let d = &s.doc()?.doc; + let mut pieces: Vec<(Piece, &Node)> = + texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id)).collect(); + // Lines: pieces turned alike and looking alike, by baseline, then left to right. + pieces.sort_by(|x, y| x.0.at.y.total_cmp(&y.0.at.y).then(x.0.at.x.total_cmp(&y.0.at.x))); + let mut lines: Vec> = vec![]; + for (piece, node) in &pieces { + let fits = |l: &Vec<(&Piece, &Node)>| { + l.first() + .is_some_and(|(f, n)| f.turned_like(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size)) + }; + match lines.iter_mut().find(|l| fits(l)) { + Some(l) => l.push((piece, node)), + None => lines.push(vec![(piece, node)]), + } + } + // Runs along each line: a wide gap or an overlap starts another. + let mut chains: Vec> = vec![]; + for mut l in lines { + l.sort_by(|x, y| x.0.at.x.total_cmp(&y.0.at.x)); + let mut chain: Vec<&Piece> = vec![]; + for (piece, _) in l { + if let Some(prev) = chain.last() { + let gap = piece.at.x - prev.end; + if gap > MAX_GAP * prev.size || gap < -MAX_OVERLAP * prev.size { + chains.push(std::mem::take(&mut chain)); + } + } + chain.push(piece); + } + chains.push(chain); + } + // Each run as one object, or as several where a piece can't keep its place joined. + let mut made: Vec<(NodeId, TextObject, Vec)> = vec![]; + let mut tries = 0; + 'chains: for chain in chains { + let mut rest: &[&Piece] = &chain; + while rest.len() > 1 { + let mut upto = rest.len(); + while let Some(part) = rest.get(..upto) { + tries += part.len(); + if tries > MAX_JOIN_TRIES { + break 'chains; + } + match merge(part) { + Ok(m) => { + let gone = part.iter().skip(1).map(|p| p.id).collect(); + if let Some(first) = part.first() { + made.push((first.id, m, gone)); + } + break; + } + // A run of one stays as it is. + Err(k) if k <= 1 => { + upto = 1; + break; + } + Err(k) => upto = k, + } + } + rest = rest.get(upto.max(1)..).unwrap_or_default(); + } + } + if made.is_empty() { + return Err(EngineError::Other("Select two or more one-line point type objects on one baseline to combine".into())); + } + let combined: usize = made.iter().map(|m| m.2.len()).sum(); + let ids: Vec = made.iter().map(|m| m.0.0).collect(); + s.edit("Combine Point Text", |d, sel| { + let mut gone = vec![]; + for (id, mut t, others) in made { + refresh_bounds(&mut t); + if let Some(n) = d.node_mut(id) { + n.kind = NodeKind::Text(Box::new(t)); + } + gone.extend(others); + } + d.remove_many(&gone)?; + sel.set(ids.iter().map(|i| NodeId(*i))); + Ok(()) + })?; + Ok(json!({ "ids": ids, "combined": combined })) +} + +fn join_text(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.joinText"; + let d = &s.doc()?.doc; + let pieces: Vec = + texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect(); + // The piece top-left on the page sets the turn; the others turned like it are read in that frame. + let on_page = |p: &Piece| Affine::new([p.turn[0], p.turn[1], p.turn[2], p.turn[3], 0.0, 0.0]) * p.at; + let first = pieces.iter().min_by(|x, y| { + let (a, b) = (on_page(x), on_page(y)); + a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)) + }); + let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| p.turned_like(f)).collect()).unwrap_or_default(); + kept.sort_by(|x, y| x.at.y.total_cmp(&y.at.y).then(x.at.x.total_cmp(&y.at.x))); + // Lines, top to bottom, by baseline; each line's pieces left to right. + let mut lines: Vec> = vec![]; + for piece in kept { + match lines.last_mut().filter(|l| l.first().is_some_and(|f| (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))) { + Some(l) => l.push(piece), + None => lines.push(vec![piece]), + } + } + for line in &mut lines { + line.sort_by(|x, y| x.at.x.total_cmp(&y.at.x)); + } + let joined: usize = lines.iter().map(Vec::len).sum(); + let (Some(top), true) = (lines.first().and_then(|l| l.first()).copied(), joined >= 2) else { + return Err(EngineError::Other("Select two or more one-line point type objects to join".into())); + }; + let mut runs: Vec = vec![]; + let mut prev_y = None; + for line in &lines { + let y = line.first().map_or(top.at.y, |p| p.at.y); + // The line keeps the distance from the baseline above as its leading. + let leading = prev_y.map(|above| y - above).filter(|l: &f64| l.is_finite() && *l > 0.0); + prev_y = Some(y); + let last = |runs: &[vectorcraft_doc::TextRun]| runs.iter().rev().find(|r| !r.text.is_empty()).map(|r| r.style.clone()).unwrap_or_default(); + if !runs.is_empty() { + runs.push(vectorcraft_doc::TextRun::new("\n", last(&runs))); + } + let start = runs.len(); + for (k, piece) in line.iter().enumerate() { + let blank = runs.last().is_some_and(|r| r.text.ends_with(char::is_whitespace)) || piece.t.plain_text().starts_with(char::is_whitespace); + if k > 0 && !blank { + runs.push(vectorcraft_doc::TextRun::new(" ", last(&runs))); + } + runs.extend(piece.t.runs.iter().cloned()); + } + if let Some(l) = leading { + for r in runs.iter_mut().skip(start) { + r.style.leading = Some(l); + } + } + } + let mut m = top.t.clone(); + m.set_all_paras(ParaStyle { justify: Justify::Left, ..top.t.para.clone() }); + m.runs = runs; + edit::normalize(&mut m.runs); + m.ruby.clear(); + // The top-left piece's first glyph stays where it was. + let [a, b, c, dd] = top.turn; + let base = Affine::new([a, b, c, dd, 0.0, 0.0]) * Affine::translate(top.at.to_vec2()); + m.xf = base; + let x0 = glyph_starting(&layout(&m), 0).map_or(0.0, |g| g.x); + m.xf = base * Affine::translate((-x0, 0.0)); + refresh_bounds(&mut m); + let id = top.id; + let gone: Vec = lines.iter().flatten().map(|p| p.id).filter(|g| *g != id).collect(); + let count = lines.len(); + s.edit("Join Point Text", |d, sel| { + if let Some(n) = d.node_mut(id) { + n.kind = NodeKind::Text(Box::new(m)); + } + d.remove_many(&gone)?; + sel.set([id]); + Ok(()) + })?; + Ok(json!({ "id": id.0, "joined": joined, "lines": count })) +} + +/// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many +/// went. +fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { + let text = t.plain_text(); + let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b)); + let Some(range) = text.get(a..b) else { return 0 }; + let mut prev = text.get(..a).and_then(|s| s.chars().next_back()); + let mut cuts = vec![]; + for (i, c) in range.char_indices() { + let at = a + i; + if c != brk { + prev = Some(c); + continue; + } + // The next character left: past the breaks that go too. + let after = at + c.len_utf8(); + let next = text.get(after..).and_then(|rest| rest.char_indices().find(|(j, n)| *n != brk || after + j >= b).map(|(_, n)| n)); + let space = prev.is_some_and(|p| !p.is_whitespace()) && next.is_some_and(|n| !n.is_whitespace()); + if space { + prev = Some(' '); + } + cuts.push((at, space)); + } + for &(at, space) in cuts.iter().rev() { + let insert = if space { " " } else { "" }; + let end = at + brk.len_utf8(); + t.splice_paras(at, end, insert); + edit::replace_range(&mut t.runs, at, end, insert); + t.ruby_after_replace(at, end, insert.len()); + } + cuts.len() +} + +fn remove_breaks(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.removeBreaks"; + let (brk, label, none) = match text_param(p, "kind", C)? { + Some("line") => ('\u{2028}', "Remove Line Breaks", "No line breaks to remove"), + Some("paragraph") => ('\n', "Remove Paragraph Breaks", "No paragraph breaks to remove"), + Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))), + None => return Err(bad(C, "missing `kind`")), + }; + // The characters a Type tool has selected, else all the text of the selected type. + let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) }; + let d = &s.doc()?.doc; + let targets: Vec<(NodeId, usize, usize)> = match editing { + Some((id, a, b)) => vec![(id, a.min(b), a.max(b))].into_iter().filter(|(id, ..)| d.is_editable(*id)).collect(), + None => texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().map(|id| (id, 0, usize::MAX)).collect(), + }; + let count: usize = targets + .iter() + .filter_map(|(id, a, b)| { + let text = text_of(d, *id)?.plain_text(); + let (a, b) = (edit::floor_char(&text, *a), edit::floor_char(&text, *b)); + Some(text.get(a..b)?.matches(brk).count()) + }) + .sum(); + if count == 0 { + return Err(EngineError::Other(none.into())); + } + if count > MAX_BREAKS { + return Err(EngineError::Other("Too many breaks to remove at once".into())); + } + let (removed, ids) = s.edit(label, |d, _| { + let (mut removed, mut ids) = (0, vec![]); + for (id, a, b) in targets { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue }; + let n = strip_breaks(t, a, b, brk); + if n > 0 { + refresh_bounds(t); + removed += n; + ids.push(id.0); + } + } + Ok((removed, ids)) + })?; + Ok(json!({ "ids": ids, "removed": removed })) +} + +/// Horizontal point type among the objects `p` names. +fn point_texts(s: &Session, p: &Value, cmd: &str) -> Result> { + let d = &s.doc()?.doc; + let ids: Vec = texts_under(d, &checked_ids_or_selection(s, p, cmd)?)? + .into_iter() + .filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))) + .collect(); + if ids.is_empty() { + return Err(EngineError::Other("Select point type".into())); + } + Ok(ids) +} + +/// Replace the type objects of `changed` as one undo step labelled `label` → their ids. +fn set_texts(s: &mut Session, label: &str, changed: Vec<(NodeId, TextObject)>, reset_angle: bool) -> Result { + let ids: Vec = changed.iter().map(|c| c.0.0).collect(); + s.edit(label, |d, _| { + for (id, mut t) in changed { + refresh_bounds(&mut t); + if let Some(n) = d.node_mut(id) { + n.kind = NodeKind::Text(Box::new(t)); + if reset_angle { + n.bbox_angle = 0.0; + } + } + } + Ok(()) + })?; + Ok(json!({ "ids": ids })) +} + +fn align_in_place(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.alignInPlace"; + let justify = match text_param(p, "align", C)? { + Some("left") => Justify::Left, + Some("center") => Justify::Center, + Some("right") => Justify::Right, + Some(other) => return Err(bad(C, format!("`align` must be \"left\", \"center\" or \"right\", not {other:?}"))), + None => return Err(bad(C, "missing `align`")), + }; + let ids = point_texts(s, p, C)?; + let d = &s.doc()?.doc; + let mut changed = vec![]; + for id in ids { + let Some(t) = text_of(d, id).filter(|t| !t.vertical && t.para_styles().any(|para| para.justify != justify)) else { continue }; + let was = layout(t); + // The longest line stays where it is. + let Some((i, line)) = was.lines.iter().enumerate().max_by(|a, b| (a.1.x1 - a.1.x0).total_cmp(&(b.1.x1 - b.1.x0))) else { continue }; + let mut n = t.clone(); + n.edit_paras(None, |para| para.justify = justify); + let Some(now) = layout(&n).lines.get(i).map(|l| l.x0) else { continue }; + n.xf *= Affine::translate((line.x0 - now, 0.0)); + changed.push((id, n)); + } + if changed.is_empty() { + return Err(EngineError::Other("The point type is aligned that way already".into())); + } + set_texts(s, "Set Alignment, Keep Position", changed, false) +} + +fn reset_transform(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.resetTextTransform"; + let scale = switch_or(p, "scale", false, C)?; + let ids = point_texts(s, p, C)?; + let d = &s.doc()?.doc; + let mut changed = vec![]; + for id in ids { + let Some(t) = text_of(d, id) else { continue }; + let [a, b, c, dd, _, _] = t.xf.as_coeffs(); + // The object's own axes: its width along its baseline, and its height square to it. + let (sx, det) = (a.hypot(b), a * dd - b * c); + if !(sx > 1e-12 && sx.is_finite() && det.is_finite() && det.abs() > 1e-12) { + continue; + } + let sy = det.abs() / sx; + let unscaled = |t: &TextObject| t.runs.iter().all(|r| r.style.h_scale == 100.0); + let upright = b.abs() <= 1e-9 * sx && c.abs() <= 1e-9 * sy && a > 0.0 && dd > 0.0; + if upright && (!scale || ((sx - sy).abs() <= 1e-9 * sy && unscaled(t))) { + continue; + } + let mut n = t.clone(); + let w = if scale { + n.runs.iter_mut().for_each(|r| r.style.h_scale = 100.0); + sy + } else { + sx + }; + // The centre of the text stays where it is. + let centre = t.xf * layout(t).bounds.center(); + let turn = Affine::scale_non_uniform(w, sy); + let now = turn * layout(&n).bounds.center(); + n.xf = Affine::translate(centre - now) * turn; + changed.push((id, n)); + } + if changed.is_empty() { + return Err(EngineError::Other("The point type has no transform to reset".into())); + } + set_texts(s, "Reset Text Transform", changed, true) +} + +fn replace_fonts(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.replaceFonts"; + let default = CharStyle::default().font_family; + let wanted = text_param(p, "font", C)?.filter(|f| !f.trim().is_empty()).unwrap_or(&default); + let db = FontDb::global(); + // Any name of the family is stored as its own name. + let family = match db.resolve(wanted, "Regular") { + Some((f, m)) if m != FontMatch::Missing => f.family.clone(), + _ => return Err(bad(C, "the replacement font is not available")), + }; + let missing = |st: &CharStyle| db.resolve(&st.font_family, &st.font_style).is_none_or(|(_, m)| m == FontMatch::Missing); + let d = &s.doc()?.doc; + let mut ids = vec![]; + for l in &d.layers { + l.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.runs.iter().any(|r| missing(&r.style)) + { + ids.push(n.id); + } + }); + } + if ids.is_empty() { + return Err(EngineError::Other("No fonts are missing".into())); + } + let runs = s.edit("Replace Missing Fonts", |d, _| { + let mut runs = 0; + for id in &ids { + let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + for r in t.runs.iter_mut().filter(|r| missing(&r.style)) { + // The style the font has closest to the one the character had. + r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone()); + r.style.font_family = family.clone(); + r.style.font_version = None; + r.style.font_axes.clear(); + runs += 1; + } + edit::normalize(&mut t.runs); + refresh_bounds(t); + } + Ok(runs) + })?; + Ok(json!({ "runs": runs, "font": family })) +} diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs new file mode 100644 index 0000000000..2286288662 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -0,0 +1,341 @@ +//! Artwork Cleanup's text tools: pieces stay where their glyphs were drawn and keep their styles, +//! each command is one undo step and refuses cleanly when there is nothing to do. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Justify, NodeId, NodeKind, TextKind, TextObject}; +use vectorcraft_geom::Point; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn text(s: &mut Session, p: Value) -> NodeId { + NodeId(s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap()) +} + +fn obj(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn ids(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +/// Each drawn character of `ids` (spaces left out) with where its glyph starts on the page, in +/// the order of the objects and their text. +fn glyphs(s: &Session, ids: &[NodeId]) -> Vec<(char, Point)> { + let mut out = vec![]; + for id in ids { + let t = obj(s, *id); + let text = t.plain_text(); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let mut gs: Vec<_> = lay.glyphs.iter().filter(|g| g.len > 0).collect(); + gs.sort_by_key(|g| g.byte); + gs.dedup_by_key(|g| g.byte); + for g in gs { + let c = text[g.byte..].chars().next().unwrap(); + if !c.is_whitespace() { + out.push((c, t.xf * g.origin)); + } + } + } + out +} + +fn assert_same_places(was: &[(char, Point)], now: &[(char, Point)]) { + assert_eq!(was.iter().map(|g| g.0).collect::(), now.iter().map(|g| g.0).collect::()); + for (a, b) in was.iter().zip(now) { + assert!((a.1 - b.1).hypot() < 0.02, "{:?} moved to {:?}", a, b); + } +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn doc_json(s: &Session) -> String { + serde_json::to_string(&s.doc().unwrap().doc.layers).unwrap() +} + +fn other(r: Result) -> String { + match r { + Err(EngineError::Other(m)) => m, + r => panic!("expected a refusal, got {r:?}"), + } +} + +#[test] +fn break_into_words_keeps_places_styles_and_is_one_step() { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 100, "text": "Hello big World", "size": 24})); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 6, "end": 9, "size": 36, "tracking": 50})).unwrap(); + let rotated = text(&mut s, json!({"x": 300, "y": 200, "text": "Turned words", "size": 18, "rotation": 30})); + let was = glyphs(&s, &[id, rotated]); + let before = doc_json(&s); + let steps = undo_steps(&s); + select(&mut s, &[id, rotated]); + let r = s.execute("addon.cleanup.breakText", &json!({"by": "words"})).unwrap(); + let pieces = ids(&r); + assert_eq!(pieces.len(), 5); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.doc().unwrap().selection.objects.len(), 5, "the pieces are selected"); + let texts: Vec = pieces.iter().map(|p| obj(&s, *p).plain_text()).collect(); + assert_eq!(texts, ["Hello", "big", "World", "Turned", "words"]); + assert_same_places(&was, &glyphs(&s, &pieces)); + let big = obj(&s, pieces[1]); + assert!(matches!(big.kind, TextKind::Point)); + assert_eq!((big.runs[0].style.size, big.runs[0].style.tracking), (36.0, 50.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_json(&s), before); +} + +#[test] +fn break_area_type_into_lines_paragraphs_and_glyphs() { + for (by, count) in [("lines", None), ("paragraphs", Some(2)), ("glyphs", None)] { + let mut s = session(); + let id = text( + &mut s, + json!({"x": 40, "y": 40, "text": "A paragraph long enough to wrap in its frame\nSecond one", "size": 14, "area": {"width": 140, "height": 200}}), + ); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.lines.len() >= 3, "the first paragraph wraps"); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + let r = s.execute("addon.cleanup.breakText", &json!({"by": by})).unwrap(); + let pieces = ids(&r); + let want = count.unwrap_or(if by == "lines" { lay.lines.len() } else { was.len() }); + assert_eq!(pieces.len(), want, "{by}"); + assert_same_places(&was, &glyphs(&s, &pieces)); + if by == "paragraphs" { + // The wrapped lines end in line breaks. + assert!(obj(&s, pieces[0]).plain_text().contains('\u{2028}')); + } + } +} + +#[test] +fn break_text_refuses_what_it_cannot_break() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + assert!(other(s.execute("addon.cleanup.breakText", &json!({}))).contains("point or area type")); + let r = s.execute("addon.cleanup.breakText", &json!({"by": "sentences"})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); +} + +#[test] +fn combine_puts_glyph_pieces_back_together_where_they_were() { + let mut s = session(); + let id = text(&mut s, json!({"x": 50, "y": 120, "text": "Water Lily", "size": 30})); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 6, "end": 10, "fill": "#ff0000"})).unwrap(); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + let pieces = ids(&s.execute("addon.cleanup.breakText", &json!({"by": "glyphs"})).unwrap()); + assert_eq!(pieces.len(), 9); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let made = ids(&r); + assert_eq!((made.len(), r["combined"].as_u64()), (1, Some(8))); + let t = obj(&s, made[0]); + assert_eq!(t.plain_text(), "Water Lily", "a space goes back between the words"); + assert_same_places(&was, &glyphs(&s, &made)); + let red = t.runs.iter().find(|r| r.text.contains('L')).unwrap(); + assert_ne!(red.style.fill, t.runs[0].style.fill, "styles stay"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(pieces[1]).is_some(), "undo brings the pieces back"); +} + +#[test] +fn combine_joins_only_pieces_on_one_line_turned_alike() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + let c = text(&mut s, json!({"x": 50, "y": 200, "text": "Below", "size": 20})); + let d = text(&mut s, json!({"x": 300, "y": 100, "text": "Turned", "size": 20, "rotation": 45})); + let was = glyphs(&s, &[a, b]); + select(&mut s, &[a, b, c, d]); + let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap(); + assert_eq!(ids(&r), [a]); + assert_eq!(obj(&s, a).plain_text(), "Left Right"); + assert_same_places(&was, &glyphs(&s, &[a])); + let doc = &s.doc().unwrap().doc; + assert!(doc.node(b).is_none() && doc.node(c).is_some() && doc.node(d).is_some()); + select(&mut s, &[c, d]); + assert!(other(s.execute("addon.cleanup.combineText", &json!({}))).contains("combine")); +} + +/// Join Point Text makes one object of stacked one-line pieces: lines top to bottom as paragraphs, +/// pieces on a line left to right, each line's baseline where it was (its leading is the distance +/// from the line above), in one undo step. A piece turned unlike the top-left one stays. +#[test] +fn join_stacks_lines_into_one_object_with_their_spacing() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20})); + let b = text(&mut s, json!({"x": 120, "y": 101, "text": "line", "size": 20})); + let c = text(&mut s, json!({"x": 50, "y": 130, "text": "Second", "size": 20})); + let d = text(&mut s, json!({"x": 50, "y": 166, "text": "Third", "size": 20})); + let turned = text(&mut s, json!({"x": 300, "y": 300, "text": "Turned", "size": 20, "rotation": 45})); + let was = glyphs(&s, &[a, c, d]); + select(&mut s, &[d, b, turned, c, a]); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.joinText", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!((r["id"].as_u64(), r["joined"].as_u64(), r["lines"].as_u64()), (Some(a.0), Some(4), Some(3))); + let t = obj(&s, a); + assert_eq!(t.plain_text(), "First line\nSecond\nThird"); + assert_eq!(t.runs.iter().filter(|r| r.text.contains("Third")).map(|r| r.style.leading).collect::>(), [Some(36.0)]); + // Each line's first glyph is where it was. + let now = glyphs(&s, &[a]); + for ch in ['F', 'S', 'T'] { + let (p, q) = (was.iter().find(|g| g.0 == ch).unwrap().1, now.iter().find(|g| g.0 == ch).unwrap().1); + assert!((p - q).hypot() < 0.05, "{ch}: {p:?} moved to {q:?}"); + } + let doc = &s.doc().unwrap().doc; + assert!(doc.node(b).is_none() && doc.node(c).is_none() && doc.node(d).is_none() && doc.node(turned).is_some()); + select(&mut s, &[turned]); + assert!(other(s.execute("addon.cleanup.joinText", &json!({}))).contains("join")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(c).is_some(), "undo brings the pieces back"); +} + +#[test] +fn remove_line_and_paragraph_breaks() { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 60, "text": "one\u{2028}two \u{2028}three\nfour\n\nfive", "size": 12})); + select(&mut s, &[id]); + let before = doc_json(&s); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "line"})).unwrap(); + assert_eq!(r["removed"], 2); + assert_eq!(obj(&s, id).plain_text(), "one two three\nfour\n\nfive"); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(r["removed"], 3); + let t = obj(&s, id); + assert_eq!((t.plain_text().as_str(), t.paragraph_count()), ("one two three four five", 1)); + assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "line"}))), "No line breaks to remove"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_json(&s), before); + assert!(matches!(s.execute("addon.cleanup.removeBreaks", &json!({})), Err(EngineError::BadParams { .. }))); +} + +/// The Type tool editing `id` with bytes `anchor..caret` selected. +fn edit_text(s: &mut Session, id: NodeId, anchor: usize, caret: usize) { + s.select_tool("type", Default::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": id.0, "anchor": anchor, "caret": caret})); +} + +#[test] +fn remove_breaks_in_the_characters_a_type_tool_selected() { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb\nc", "size": 12})); + select(&mut s, &[id]); + edit_text(&mut s, id, 0, 2); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "a b\nc"); +} + +#[test] +fn split_at_the_cursor_and_around_a_selection() { + for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 60, "text": "Split here please", "size": 20, "justify": "center"})); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + let r = s.execute("addon.cleanup.splitText", &json!({})); + assert!(matches!(&r, Err(EngineError::Disabled(_, why)) if why.contains("Type tool")), "{r:?}"); + edit_text(&mut s, id, anchor, caret); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.splitText", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let pieces = ids(&r); + let texts: Vec = pieces.iter().map(|p| obj(&s, *p).plain_text()).collect(); + assert_eq!(texts, want); + assert_same_places(&was, &glyphs(&s, &pieces)); + assert!(s.tool_options()["editing"].is_null(), "editing ends"); + } +} + +#[test] +fn split_keeps_the_later_lines_of_a_wrapped_piece() { + let mut s = session(); + let id = text( + &mut s, + json!({"x": 40, "y": 40, "text": "First words then a long run of text that wraps in the frame", "size": 14, "area": {"width": 160, "height": 200}}), + ); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + edit_text(&mut s, id, 6, 6); + let pieces = ids(&s.execute("addon.cleanup.splitText", &json!({})).unwrap()); + assert_eq!(pieces.len(), 2); + assert_same_places(&was, &glyphs(&s, &pieces)); +} + +#[test] +fn set_alignment_keeps_the_text_in_place() { + let mut s = session(); + let id = text(&mut s, json!({"x": 100, "y": 60, "text": "Stay put", "size": 20})); + let multi = text(&mut s, json!({"x": 100, "y": 160, "text": "Short\u{2028}The longest line", "size": 20})); + let was = glyphs(&s, &[id]); + let longest: Vec<_> = glyphs(&s, &[multi]).into_iter().skip(5).collect(); + select(&mut s, &[id, multi]); + for align in ["center", "right", "left"] { + s.execute("addon.cleanup.alignInPlace", &json!({"align": align})).unwrap(); + assert_same_places(&was, &glyphs(&s, &[id])); + assert_same_places(&longest, &glyphs(&s, &[multi]).into_iter().skip(5).collect::>()); + } + assert_eq!(obj(&s, id).para.justify, Justify::Left); + assert!(other(s.execute("addon.cleanup.alignInPlace", &json!({"align": "left"}))).contains("already")); + assert!(matches!(s.execute("addon.cleanup.alignInPlace", &json!({"align": "up"})), Err(EngineError::BadParams { .. }))); +} + +#[test] +fn reset_text_transform_takes_off_rotation_and_with_scale_the_horizontal_scale() { + let mut s = session(); + let id = text(&mut s, json!({"x": 100, "y": 100, "text": "Tilted", "size": 20, "rotation": 30})); + s.execute("text.setRangeStyle", &json!({"id": id.0, "hScale": 150})).unwrap(); + let centre = |s: &Session| { + let t = obj(s, id); + t.xf * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds.center() + }; + let was = centre(&s); + let size = obj(&s, id).effective_char_style(&obj(&s, id).runs[0].style).unwrap().size; + select(&mut s, &[id]); + s.execute("addon.cleanup.resetTextTransform", &json!({})).unwrap(); + let t = obj(&s, id); + let [_, b, c, _, _, _] = t.xf.as_coeffs(); + assert!(b.abs() < 1e-9 && c.abs() < 1e-9, "{:?}", t.xf); + assert!((centre(&s) - was).hypot() < 1e-6); + assert!((t.effective_char_style(&t.runs[0].style).unwrap().size - size).abs() < 1e-6, "the size stays"); + assert!(t.runs[0].style.h_scale > 100.0, "the horizontal scale stays"); + assert!(other(s.execute("addon.cleanup.resetTextTransform", &json!({}))).contains("no transform")); + s.execute("addon.cleanup.resetTextTransform", &json!({"scale": true})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.h_scale, 100.0); +} + +#[test] +fn replace_missing_fonts_with_the_default_or_a_chosen_font() { + let mut s = session(); + let gone = text(&mut s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family", "style": "Bold"})); + let kept = text(&mut s, json!({"x": 40, "y": 120, "text": "Fine", "size": 20})); + let fine = obj(&s, kept); + let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap(); + assert_eq!((r["runs"].as_u64(), r["font"].as_str()), (Some(1), Some("Source Sans 3"))); + let t = obj(&s, gone); + assert_eq!((t.runs[0].style.font_family.as_str(), t.runs[0].style.font_style.as_str()), ("Source Sans 3", "Bold")); + assert_eq!(obj(&s, kept), fine); + assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing"); + let r = s.execute("addon.cleanup.replaceFonts", &json!({"font": "No Such Font Family"})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); +} diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs new file mode 100644 index 0000000000..3dc037a2fa --- /dev/null +++ b/crates/engine/src/cmd/addons/color.rs @@ -0,0 +1,153 @@ +//! Color Effects (`addon.color.*`), a built-in add-on: its live effects (Exposure, Desaturate, +//! Duotone and Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as +//! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the +//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model, +//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, and Find Nearest +//! Swatch ([`nearest`]) matches colours to a swatch library's. Its panel and its submenu, Object › +//! Plug-ins › Color Effects, are the UI's. + +mod nearest; +mod print_fixes; +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_render::effects; + +use super::super::colorcmds::recolor_links; +use super::super::select::walk_selectable; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, text_param}; +use crate::{Result, Session}; + +/// The kinds Select by Color Kind selects (`addon.color.select`). +pub const SELECT_KINDS: [&str; 5] = ["spotColors", "colorEffects", "rgbImages", "cmykImages", "grayImages"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.color.select", + "Select by Color Kind", + ["Object", "Plug-ins", "Color Effects"], + None, + "{kind: \"spotColors\" (objects painted with a spot colour swatch, solid or in a gradient's stops) | \"colorEffects\" (objects carrying a visible colour adjustment effect, on themselves or on a fill or stroke) | \"rgbImages\" | \"cmykImages\" | \"grayImages\" (embedded or linked images whose pixels are RGB, CMYK, or grayscale or 1-bit)} select those objects among the ones Select All reaches, inside groups too; locked and hidden ones are left out → {count}", + has_doc, + select + ), + cmd!( + "addon.color.filter", + "Apply as Filter", + ["Object", "Plug-ins", "Color Effects"], + None, + "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay. Duotone links a colour to its one tone's swatch as the live effect does → {changed}", + has_selection, + filter + ), + cmd!( + "addon.color.printFixes", + "Print Ink Fixes", + ["Object", "Plug-ins", "Color Effects"], + None, + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + has_doc, + print_fixes::run + ), + cmd!( + query "addon.color.nearestSwatch", + "Find Nearest Swatch", + ["Object", "Plug-ins", "Color Effects"], + None, + "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}", + has_doc, + nearest::find + ), + cmd!( + "addon.color.applyNearestSwatch", + "Apply Nearest Swatch", + ["Object", "Plug-ins", "Color Effects"], + None, + "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", + has_selection, + nearest::apply + ), + ] +} + +fn select(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.color.select"; + let kind = text_param(p, "kind", C)?.ok_or_else(|| bad(C, "missing `kind`"))?; + if !SELECT_KINDS.contains(&kind) { + return Err(bad(C, "`kind` must be spotColors, colorEffects, rgbImages, cmykImages or grayImages")); + } + let st = s.doc()?; + let mut ids: Vec = vec![]; + walk_selectable(&st.doc, st.isolation, |n| { + if is_of_kind(&st.doc, n, kind) { + ids.push(n.id); + // An object taken whole: what is inside it isn't taken again. + return false; + } + true + }); + s.select(|_, sel| sel.set(ids))?; + Ok(json!({ "count": s.doc()?.selection.objects.len() })) +} + +/// Is `n` an object of Select by Color Kind's `kind`? Containers count for colour effects only: +/// for the other kinds, the objects inside them are looked at one by one. +fn is_of_kind(d: &Document, n: &Node, kind: &str) -> bool { + match kind { + "colorEffects" => effects::has_adjustment(n), + "spotColors" if !n.is_container() => { + let mut spot = false; + vectorcraft_doc::swatches::node_colors(n, &mut |_, swatch| { + spot |= swatch.is_some_and(|name| d.swatch(name).is_some_and(|w| w.spot)); + }); + spot + } + _ => { + let NodeKind::Image(img) = &n.kind else { return false }; + let Some(blob) = d.images.get(&img.key) else { return false }; + let model = if blob.is_cmyk() { + "cmykImages" + } else if is_gray(&blob.bytes) { + "grayImages" + } else { + "rgbImages" + }; + model == kind + } + } +} + +/// Are the encoded image `bytes` grayscale or 1-bit? Reads only the header. +fn is_gray(bytes: &[u8]) -> bool { + use image::ImageDecoder as _; + let decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok()); + decoder.is_some_and(|d| matches!(d.color_type(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16)) +} + +fn filter(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.color.filter"; + let id = text_param(p, "effect", C)?.ok_or_else(|| bad(C, "missing `effect`"))?; + if !effects::is_adjustment(id) { + return Err(bad(C, format!("`{id}` is not a colour adjustment"))); + } + let params = match p.get("params") { + None | Some(Value::Null) => json!({}), + Some(v @ Value::Object(_)) => v.clone(), + Some(_) => return Err(bad(C, "`params` must be an object")), + }; + let fx = effects::new_effect(id, ¶ms).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?; + let ids = checked_ids_or_selection(s, p, C)?; + // Settings that change nothing still make the pass, which then leaves every colour as it was. + let Some(map) = effects::color_map(&[fx]) else { return Ok(json!({ "changed": 0 })) }; + let mut given = p.clone(); + if let Some(o) = given.as_object_mut() { + o.insert("ids".into(), json!(ids.iter().map(|i| i.0).collect::>())); + } + let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); + let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc); + let swatches = |name: &str| kinds.get(name).copied(); + recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) +} diff --git a/crates/engine/src/cmd/addons/color/nearest.rs b/crates/engine/src/cmd/addons/color/nearest.rs new file mode 100644 index 0000000000..5a9d0e7c75 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/nearest.rs @@ -0,0 +1,198 @@ +//! Find Nearest Swatch (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`; Object › +//! Plug-ins › Color Effects › Find Nearest Swatch…): the swatches of a library, a colour book the +//! user loaded or the document closest to each colour of the selection (CIEDE2000), and the +//! colours replaced by them as one undo step (#4923). + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{Lab, delta_e2000}; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::swatches::color_name; +use vectorcraft_doc::{Document, NodeId, NodeKind}; + +use super::super::super::colorcmds::recolor_links; +use super::super::super::menucmds::squash; +use super::super::super::swatchlib::{DOCUMENT_SWATCHES, library_swatches}; +use super::super::super::{bad, checked_ids_or_selection, color_value, index, switch_or, text_param}; +use super::super::arrange::whole_in; +use crate::{Result, Session}; + +const FIND: &str = "addon.color.nearestSwatch"; +const APPLY: &str = "addon.color.applyNearestSwatch"; +/// The most colours of the selection looked up. +const MAX_COLORS: usize = 100; + +/// The `library` param ([`DOCUMENT_SWATCHES`] when left out) and its colour swatches with their Lab +/// values. +fn candidates(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec<(Swatch, Lab)>)> { + let key = text_param(p, "library", cmd)?.unwrap_or(DOCUMENT_SWATCHES).to_string(); + let swatches = library_swatches(s, &key).ok_or_else(|| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list)")))?; + let labs: Vec<(Swatch, Lab)> = swatches + .into_iter() + .filter(|w| !w.is_reserved()) + .filter_map(|w| { + let lab = w.paint.color()?.to_lab(); + Some((w, lab)) + }) + .collect(); + if labs.is_empty() { + return Err(bad(cmd, format!("`{key}` has no colours"))); + } + Ok((key, labs)) +} + +/// The `count` swatches of `among` closest to `c`, closest first, with their difference (ΔE 2000). +fn nearest(among: &[(Swatch, Lab)], c: Color, count: usize) -> Vec<(&Swatch, f32)> { + let lab = c.to_lab(); + let mut v: Vec<(&Swatch, f32)> = among.iter().map(|(w, l)| (w, delta_e2000(*l, lab))).collect(); + v.sort_by(|a, b| a.1.total_cmp(&b.1)); + v.truncate(count); + v +} + +/// The solid colours and gradient stops of the fills (`fill`) and strokes (`stroke`) of `ids`, of +/// everything inside them and of their type, once each and at most [`MAX_COLORS`]. +fn art_colors(d: &Document, ids: &[NodeId], fill: bool, stroke: bool) -> Vec { + let mut out: Vec = vec![]; + let mut add = |p: &Paint| { + let colors: Vec = match p { + Paint::Solid { color, .. } => vec![*color], + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(), + _ => vec![], + }; + for c in colors { + if out.len() < MAX_COLORS && !out.contains(&c) { + out.push(c); + } + } + }; + for n in ids.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |m| { + for it in &m.appearance.items { + if if it.is_fill() { fill } else { stroke } { + add(it.paint()); + } + } + if let NodeKind::Text(t) = &m.kind { + for r in &t.runs { + if fill { + add(&r.style.fill); + } + if stroke { + add(&r.style.stroke); + } + } + } + }); + } + out +} + +/// A swatch's name and values as the results give them. +fn described(w: &Swatch) -> Value { + let c = w.paint.color().unwrap_or_default(); + json!({ "name": w.name, "values": color_name(c), "hex": c.to_hex(), "spot": w.spot }) +} + +pub(super) fn find(s: &mut Session, p: &Value) -> Result { + let count = whole_in(p, "count", (1, 50), FIND)?.map_or(5, index); + let (fill, stroke) = (switch_or(p, "fill", true, FIND)?, switch_or(p, "stroke", true, FIND)?); + let colors = match p.get("color").filter(|v| !v.is_null()) { + Some(v) => vec![color_value(v).ok_or_else(|| bad(FIND, "`color` is not a colour"))?], + None => { + let ids = checked_ids_or_selection(s, p, FIND)?; + if ids.is_empty() { + return Err(bad(FIND, "select objects or give `color`")); + } + art_colors(&s.doc()?.doc, &ids, fill, stroke) + } + }; + let (library, among) = candidates(s, p, FIND)?; + let found: Vec = colors + .iter() + .map(|c| { + let matches: Vec = nearest(&among, *c, count) + .into_iter() + .map(|(w, de)| { + let mut m = described(w); + m["deltaE"] = json!((f64::from(de) * 100.0).round() / 100.0); + m + }) + .collect(); + json!({ "values": color_name(*c), "hex": c.to_hex(), "matches": matches }) + }) + .collect(); + Ok(json!({ "library": library, "colors": found })) +} + +pub(super) fn apply(s: &mut Session, p: &Value) -> Result { + let (fill, stroke) = (switch_or(p, "fill", true, APPLY)?, switch_or(p, "stroke", true, APPLY)?); + let ids = checked_ids_or_selection(s, p, APPLY)?; + if ids.is_empty() { + return Err(bad(APPLY, "nothing selected")); + } + let (library, among) = candidates(s, p, APPLY)?; + // The swatch each colour takes, once each. + let colors = art_colors(&s.doc()?.doc, &ids, fill, stroke); + let mut used: Vec<&Swatch> = vec![]; + for c in &colors { + if let Some((w, _)) = nearest(&among, *c, 1).first() + && !used.iter().any(|u| u.name == w.name) + { + used.push(w); + } + } + if used.is_empty() { + return Ok(json!({ "changed": 0, "swatches": [], "added": [] })); + } + let undo = s.doc()?.history.undo.len(); + // A library's swatches join the document's first, as Add to Swatches adds them, so spot and + // global colours stay linked to theirs. + let mut added = vec![]; + let mut names: Vec = used.iter().map(|w| w.name.clone()).collect(); + if library != DOCUMENT_SWATCHES { + let r = s.execute("swatch.library.add", &json!({ "library": library, "names": names }))?; + let listed = |k: &str| r.get(k).and_then(Value::as_array).cloned().unwrap_or_default(); + let in_doc: Vec = listed("added").iter().chain(&listed("existing")).filter_map(Value::as_str).map(str::to_string).collect(); + let d = &s.doc()?.doc; + // Each library swatch's copy: the document swatch with its paint among those added or kept. + names = used + .iter() + .map(|w| in_doc.iter().find(|n| d.swatch(n).is_some_and(|x| x.paint == w.paint)).cloned().unwrap_or_else(|| w.name.clone())) + .collect(); + added = listed("added"); + } + // Each used swatch's paint as art takes it: linked to a global or spot swatch. + let d = &s.doc()?.doc; + let paints: Vec<(Lab, Paint)> = used + .iter() + .zip(&names) + .filter_map(|(w, name)| { + let lab = w.paint.color()?.to_lab(); + let paint = d.swatch(name).filter(|x| x.global).and_then(|_| d.tint_paint(name, 1.0)).unwrap_or_else(|| w.paint.clone()); + Some((lab, paint)) + }) + .collect(); + // shortcut: a colour past the MAX_COLORS looked up takes the closest of the swatches those + // took; look up every colour if documents with more colours need their own matches. + let to = |c: Color| -> Option<&Paint> { + let lab = c.to_lab(); + paints.iter().min_by(|a, b| delta_e2000(a.0, lab).total_cmp(&delta_e2000(b.0, lab))).map(|(_, p)| p) + }; + let links = |c: &mut Color, link: &mut Option, tint: &mut f32| { + let Some(Paint::Solid { color, swatch, .. }) = to(*c) else { return false }; + if *c == *color && *link == *swatch { + return false; + } + (*c, *link, *tint) = (*color, swatch.clone(), 1.0); + true + }; + let given = json!({ + "ids": ids.iter().map(|i| i.0).collect::>(), "fill": fill, "stroke": stroke, "includeImages": false, "includePatterns": false, + }); + let r = recolor_links(s, &given, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?; + squash(s, undo, "Apply Nearest Swatch"); + Ok(json!({ "changed": r["changed"], "swatches": names, "added": added })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/nearest/tests.rs b/crates/engine/src/cmd/addons/color/nearest/tests.rs new file mode 100644 index 0000000000..0436d19c89 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/nearest/tests.rs @@ -0,0 +1,115 @@ +//! Find Nearest Swatch. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +const FIND: &str = "addon.color.nearestSwatch"; +const APPLY: &str = "addon.color.applyNearestSwatch"; + +/// A document with a global swatch "Brand" and a selected rectangle filled `fill`, stroked `stroke`. +fn doc(fill: &str, stroke: Option<&str>) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": fill})).unwrap(); + match stroke { + Some(c) => s.execute("paint.setStroke", &json!({"color": c})).unwrap(), + None => s.execute("paint.setStroke", &json!({"none": true})).unwrap(), + }; + (s, id) +} + +fn paints(s: &Session, id: NodeId) -> (Paint, Paint) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + (n.appearance.fill_paint(), n.appearance.items.iter().find(|i| !i.is_fill()).unwrap().paint().clone()) +} + +fn names(matches: &Value) -> Vec<&str> { + matches.as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap()).collect() +} + +#[test] +fn the_closest_swatches_of_a_library_are_listed_closest_first() { + let (mut s, _) = doc("#ff6634", None); + let v = s.execute(FIND, &json!({"library": "web-safe-216", "count": 3})).unwrap(); + assert_eq!(v["library"], "web-safe-216"); + let colors = v["colors"].as_array().unwrap(); + assert_eq!(colors.len(), 1, "the fill; no stroke"); + assert_eq!((colors[0]["hex"].as_str(), colors[0]["values"].as_str()), (Some("#ff6634"), Some("R=255 G=102 B=52"))); + let m = &colors[0]["matches"]; + assert_eq!(names(m)[0], "#FF6633"); + let de: Vec = m.as_array().unwrap().iter().map(|x| x["deltaE"].as_f64().unwrap()).collect(); + assert_eq!(de.len(), 3); + assert!(de[0] < 1.0 && de.windows(2).all(|w| w[0] <= w[1]), "{de:?}"); + // A colour given is looked up instead of the selection's. + let v = s.execute(FIND, &json!({"library": "web-safe-216", "color": "#010203", "count": 1})).unwrap(); + assert_eq!(names(&v["colors"][0]["matches"]), ["#000000"]); +} + +#[test] +fn the_document_swatches_are_the_default_library() { + let (mut s, _) = doc("#ff8010", Some("#ff8010")); + let v = s.execute(FIND, &json!({})).unwrap(); + assert_eq!(v["library"], "document"); + assert_eq!(v["colors"].as_array().unwrap().len(), 1, "fill and stroke share a colour: looked up once"); + assert_eq!(names(&v["colors"][0]["matches"])[0], "Brand"); + assert!(!names(&v["colors"][0]["matches"]).contains(&"[Registration]")); +} + +#[test] +fn applying_links_each_colour_to_its_nearest_document_swatch_as_one_undo_step() { + let (mut s, id) = doc("#ff8010", Some("#ff8010")); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(APPLY, &json!({"stroke": false})).unwrap(); + assert_eq!((v["changed"].as_u64(), v["swatches"].clone(), v["added"].clone()), (Some(1), json!(["Brand"]), json!([]))); + let (fill, stroke) = paints(&s, id); + assert!(matches!(&fill, Paint::Solid { swatch: Some(n), color, .. } if n == "Brand" && color.to_hex() == "#ff8000"), "{fill:?}"); + assert_eq!(stroke.color().unwrap().to_hex(), "#ff8010", "strokes left alone"); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Apply Nearest Swatch")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paints(&s, id).0.color().unwrap().to_hex(), "#ff8010"); +} + +#[test] +fn a_library_spot_colour_joins_the_document_and_stays_spot() { + let (mut s, id) = doc("#e01525", None); + // A colour book of one spot colour, loaded as a user would load one they own. + s.execute("swatch.new", &json!({"name": "Ink Red", "color": "#e01020", "spot": true})).unwrap(); + let data = s.execute("swatch.library.save", &json!({"names": ["Ink Red"]})).unwrap()["data"].as_str().unwrap().to_string(); + s.execute("swatch.delete", &json!({"names": ["Ink Red"]})).unwrap(); + let lib = s.execute("swatch.library.load", &json!({"data": data, "name": "Book.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(APPLY, &json!({"library": lib})).unwrap(); + assert_eq!((v["swatches"].clone(), v["added"].clone()), (json!(["Ink Red"]), json!(["Ink Red"]))); + let d = &s.doc().unwrap().doc; + assert!(d.swatch("Ink Red").is_some_and(|w| w.spot && w.global)); + assert!(matches!(paints(&s, id).0, Paint::Solid { swatch: Some(n), .. } if n == "Ink Red")); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "adding and applying undo together"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Ink Red").is_none()); + assert_eq!(paints(&s, id).0, Paint::solid(Color::from_hex("#e01525").unwrap())); +} + +#[test] +fn bad_requests_are_refused() { + let (mut s, _) = doc("#ff8010", None); + for (p, why) in [ + (json!({"library": "nope"}), "no swatch library `nope`"), + (json!({"library": "spectrum-gradients"}), "has no colours"), + (json!({"count": 0}), "`count` must be from 1 to 50"), + (json!({"color": "zzz"}), "`color` is not a colour"), + (json!({"fill": "yes"}), "`fill` must be true or false"), + ] { + let e = s.execute(FIND, &p).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute(FIND, &json!({})).unwrap_err().to_string().contains("select objects or give `color`")); + assert!(s.execute(APPLY, &json!({})).is_err(), "nothing selected"); +} diff --git a/crates/engine/src/cmd/addons/color/print_fixes.rs b/crates/engine/src/cmd/addons/color/print_fixes.rs new file mode 100644 index 0000000000..7a4cfee9c4 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/print_fixes.rs @@ -0,0 +1,170 @@ +//! Print Ink Fixes (`addon.color.printFixes`, Object › Plug-ins › Color Effects › Print Ink +//! Fixes…): a CMYK document's inks made ready for print in one undo step. Colours with more total +//! ink than the limit are scaled down to it, white fills and strokes stop overprinting, and black +//! ones start to, as Edit › Edit Colors › Overprint Black sets it. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_doc::overprint::{OverprintBlack, is_white}; +use vectorcraft_doc::{ColorMode, Node, NodeKind}; + +use super::super::super::colorcmds::{Recolor, Scope}; +use super::super::super::overprint::edit_counted; +use super::super::super::{bad, checked_ids_or_selection, number_or, switch_or, text_param}; +use crate::{Result, Session}; + +const C: &str = "addon.color.printFixes"; + +/// What `p` asks for. +struct Fixes { + /// Most total ink, 0..4 (0: off). + ink_limit: f32, + exclude_pure_black: bool, + remove_white_overprint: bool, + /// Overprint Black's least black, 0..1 (0: off). + overprint_black: f32, + text_only: bool, + fill: bool, + stroke: bool, +} + +/// The percentage `p` gives for `key` in 0..=`max`, as a fraction (0 when left out). +fn percent(p: &Value, key: &str, max: f64) -> Result { + let v = number_or(p, key, 0.0, C)?; + if !(0.0..=max).contains(&v) { + return Err(bad(C, format!("`{key}` must be 0..{max}"))); + } + Ok((v / 100.0) as f32) +} + +impl Fixes { + fn of(p: &Value) -> Result { + let f = Fixes { + ink_limit: percent(p, "inkLimit", 400.0)?, + exclude_pure_black: switch_or(p, "excludePureBlack", true, C)?, + remove_white_overprint: switch_or(p, "removeWhiteOverprint", false, C)?, + overprint_black: percent(p, "overprintBlack", 100.0)?, + text_only: switch_or(p, "textOnly", false, C)?, + fill: switch_or(p, "fill", true, C)?, + stroke: switch_or(p, "stroke", true, C)?, + }; + if f.ink_limit <= 0.0 && f.overprint_black <= 0.0 && !f.remove_white_overprint { + return Err(bad(C, "give `inkLimit`, `removeWhiteOverprint` or `overprintBlack`")); + } + Ok(f) + } + + /// `c` with its total ink scaled down to the limit: CMYK, and grey (black ink) unless + /// pure blacks are excluded, which CMYK with black ink only is too. + fn limit(&self, c: Color) -> Color { + const E: f32 = 0.005; + let max = self.ink_limit; + match c { + Color::Cmyk { c: cy, m, y, k } => { + let total = cy + m + y + k; + let pure_black = cy <= E && m <= E && y <= E; + if total <= max || (self.exclude_pure_black && pure_black) || !total.is_finite() { + return c; + } + let s = max / total; + Color::cmyk(cy * s, m * s, y * s, k * s) + } + Color::Gray { k } if k > max && !self.exclude_pure_black => Color::gray(max), + _ => c, + } + } + + /// Remove white overprint from `n`'s own fills and strokes and its characters': true when + /// that changed anything. + fn unset_white(&self, n: &mut Node) -> bool { + let mut changed = false; + let mut off = |aimed: bool, white: bool, flag: &mut bool| { + if aimed && white && *flag { + *flag = false; + changed = true; + } + }; + for it in &mut n.appearance.items { + let aimed = if it.is_fill() { self.fill } else { self.stroke }; + let white = is_white(it.paint()); + off(aimed, white, it.overprint_mut()); + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + off(self.fill, is_white(&r.style.fill), &mut r.style.overprint_fill); + off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke); + } + } + changed + } + + /// The overprint fixes on `n` and everything inside it: (objects whose white overprint was + /// removed, objects set to overprint black). + fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String]) -> (usize, usize) { + let white = usize::from(self.remove_white_overprint && self.unset_white(n)); + let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_))); + let mut counts = (white, usize::from(blacks && black.apply(n, spots))); + for c in n.children_mut().into_iter().flatten() { + let (w, b) = self.overprint(Arc::make_mut(c), black, spots); + counts = (counts.0 + w, counts.1 + b); + } + counts + } +} + +pub(super) fn run(s: &mut Session, p: &Value) -> Result { + let fixes = Fixes::of(p)?; + let st = s.doc()?; + if st.doc.color_mode != ColorMode::Cmyk { + return Err(bad(C, "Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first")); + } + let layers = st.doc.layers.iter().map(|l| l.id).collect(); + let roots = checked_ids_or_selection(s, p, C)?; + // As Artwork Cleanup's: the selection, or the document while nothing is selected. + let ids = match text_param(p, "scope", C)? { + Some("document") => layers, + None if roots.is_empty() => layers, + Some("selection") if roots.is_empty() => return Err(bad(C, "nothing selected")), + Some("selection") | None => roots, + Some(other) => return Err(bad(C, format!("`scope` must be \"selection\" or \"document\", not {other:?}"))), + }; + let black = OverprintBlack { min_k: fixes.overprint_black, fill: fixes.fill, stroke: fixes.stroke, ..OverprintBlack::default() }; + let (mut ink, mut white, mut blacks) = (0, 0, 0); + let changed = edit_counted(s, "Print Ink Fixes", |d| { + if fixes.ink_limit > 0.0 { + let spots = d.spot_names(); + // Spot inks and Registration aren't process ink: they keep their colour and link. + let links = |c: &mut Color, link: &mut Option, _: &mut f32| { + if link.as_ref().is_some_and(|n| n == REGISTRATION || spots.contains(n)) { + return false; + } + let new = fixes.limit(*c); + if new == *c { + return false; + } + (*c, *link) = (new, None); + true + }; + let scope = Scope { fill: fixes.fill, stroke: fixes.stroke, images: false, patterns: false }; + ink = Recolor::with_links(scope, &|c| fixes.limit(c), &links).run(d, &ids); + } + if !fixes.remove_white_overprint && fixes.overprint_black <= 0.0 { + return Ok(ink); + } + let spots = d.spot_names(); + for id in &ids { + if let Some(n) = d.node_mut(*id) { + let (w, b) = fixes.overprint(n, &black, &spots); + (white, blacks) = (white + w, blacks + b); + } + } + Ok(ink + white + blacks) + })?; + Ok(json!({ "changed": changed, "inkLimited": ink, "whiteOverprintRemoved": white, "blackOverprinted": blacks })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs new file mode 100644 index 0000000000..e4c1915879 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs @@ -0,0 +1,129 @@ +//! Print Ink Fixes. + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::NodeId; + +use crate::Session; + +const C: &str = "addon.color.printFixes"; + +/// A CMYK document with a rectangle per fill, each with overprint as given; nothing selected. +fn doc(fills: &[(Value, bool)]) -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let ids = fills + .iter() + .enumerate() + .map(|(i, (fill, overprint))| { + let id = s.execute("shape.rectangle", &json!({"x": 10 + 30 * i, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({ "color": fill })).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.setOverprint", &json!({ "fill": overprint })).unwrap(); + NodeId(id) + }) + .collect(); + s.execute("select.none", &json!({})).unwrap(); + (s, ids) +} + +fn fill(s: &Session, id: NodeId) -> (Color, bool) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let item = n.appearance.items.iter().find(|i| i.is_fill()).unwrap().clone(); + (item.paint().color().unwrap(), item.overprint()) +} + +fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value { + json!({"c": c, "m": m, "y": y, "k": k}) +} + +fn close(a: Color, b: [f32; 4]) -> bool { + let Color::Cmyk { c, m, y, k } = a else { return false }; + [c, m, y, k].iter().zip(b).all(|(x, y)| (x - y).abs() < 0.001) +} + +#[test] +fn the_ink_limit_scales_heavy_colours_down_to_it() { + let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), false), (cmyk(40.0, 30.0, 20.0, 10.0), false), (cmyk(0.0, 0.0, 0.0, 80.0), false)]); + let undo = s.doc().unwrap().history.undo.len(); + // Nothing selected: the whole document. + let v = s.execute(C, &json!({"inkLimit": 300})).unwrap(); + assert_eq!((v["inkLimited"].clone(), v["changed"].clone()), (json!(1), json!(1))); + assert!(close(fill(&s, ids[0]).0, [0.75; 4]), "{:?}", fill(&s, ids[0])); + assert!(close(fill(&s, ids[1]).0, [0.4, 0.3, 0.2, 0.1]), "under the limit: as it was"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + // The selection only. + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + s.execute(C, &json!({"inkLimit": 50})).unwrap(); + assert!(close(fill(&s, ids[1]).0, [0.2, 0.15, 0.1, 0.05])); + assert!(close(fill(&s, ids[0]).0, [0.75; 4]), "left out"); + // Pure black keeps its ink unless it is included. + s.execute(C, &json!({"inkLimit": 50, "scope": "document"})).unwrap(); + assert!(close(fill(&s, ids[0]).0, [0.125; 4])); + assert!(close(fill(&s, ids[2]).0, [0.0, 0.0, 0.0, 0.8])); + s.execute(C, &json!({"inkLimit": 50, "scope": "document", "excludePureBlack": false})).unwrap(); + assert!(close(fill(&s, ids[2]).0, [0.0, 0.0, 0.0, 0.5])); +} + +#[test] +fn spot_and_registration_colours_keep_their_ink() { + let (mut s, ids) = doc(&[(cmyk(0.0, 0.0, 0.0, 0.0), false), (cmyk(0.0, 0.0, 0.0, 0.0), false)]); + s.execute("swatch.new", &json!({"name": "Heavy", "color": cmyk(100.0, 100.0, 100.0, 50.0), "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [ids[0].0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Heavy"})).unwrap(); + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "[Registration]"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = [fill(&s, ids[0]), fill(&s, ids[1])]; + assert_eq!(s.execute(C, &json!({"inkLimit": 200})).unwrap()["changed"], 0); + assert_eq!([fill(&s, ids[0]), fill(&s, ids[1])], before); +} + +#[test] +fn white_overprint_goes_and_black_overprint_comes_at_the_threshold() { + let white = cmyk(0.0, 0.0, 0.0, 0.0); + let (mut s, ids) = + doc(&[(white.clone(), true), (cmyk(0.0, 0.0, 0.0, 95.0), false), (cmyk(0.0, 0.0, 0.0, 80.0), false), (cmyk(30.0, 0.0, 0.0, 100.0), false)]); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(C, &json!({"removeWhiteOverprint": true, "overprintBlack": 90})).unwrap(); + assert_eq!((v["whiteOverprintRemoved"].clone(), v["blackOverprinted"].clone()), (json!(1), json!(1)), "{v}"); + let overprints: Vec = ids.iter().map(|id| fill(&s, *id).1).collect(); + // White stops; 95 % black starts; 80 % is under the threshold; a rich black isn't pure black. + assert_eq!(overprints, [false, true, false, false]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(ids.iter().map(|id| fill(&s, *id).1).collect::>(), [true, false, false, false]); + // On type only: the rectangles stay. + let v = s.execute(C, &json!({"overprintBlack": 90, "textOnly": true})).unwrap(); + assert_eq!(v["changed"], 0); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed, no undo step"); + // Strokes only: the fills stay. + assert_eq!(s.execute(C, &json!({"overprintBlack": 90, "fill": false})).unwrap()["changed"], 0); +} + +#[test] +fn bad_requests_and_rgb_documents_are_refused() { + let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), true)]); + for p in [ + json!({}), + json!({"inkLimit": 0}), + json!({"inkLimit": "300"}), + json!({"inkLimit": 401}), + json!({"inkLimit": -1}), + json!({"overprintBlack": 101}), + json!({"overprintBlack": true}), + json!({"removeWhiteOverprint": "yes"}), + json!({"inkLimit": 300, "fill": 1}), + json!({"inkLimit": 300, "scope": "page"}), + json!({"inkLimit": 300, "scope": "selection"}), + json!({"inkLimit": 300, "ids": [999_999]}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + } + assert!(close(fill(&s, ids[0]).0, [1.0; 4])); + let mut rgb = Session::new(); + rgb.execute("file.new", &json!({})).unwrap(); + rgb.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let e = rgb.execute(C, &json!({"inkLimit": 300})).unwrap_err().to_string(); + assert!(e.contains("CMYK"), "{e}"); +} diff --git a/crates/engine/src/cmd/addons/color/tests.rs b/crates/engine/src/cmd/addons/color/tests.rs new file mode 100644 index 0000000000..ed8137d6a9 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/tests.rs @@ -0,0 +1,316 @@ +//! Color Effects: its live effects through effect.apply, and Apply as Filter. + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A document with a selected red rectangle, unstroked. +fn red_rect() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + (s, id) +} + +fn fill_hex(s: &Session, id: NodeId) -> String { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color().unwrap().to_hex() +} + +fn pixel(s: &Session) -> [u8; 4] { + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true).pixel(50, 50) +} + +#[test] +fn the_live_effects_draw_without_changing_the_colours() { + for (effect, params, drawn) in [ + ("addon.color.invert", json!({}), [0, 255, 255, 255]), + ("addon.color.desaturate", json!({}), [128, 128, 128, 255]), + ("addon.color.exposure", json!({"exposure": -20}), [0, 0, 0, 255]), + ] { + let (mut s, id) = red_rect(); + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + assert_eq!(fill_hex(&s, id), "#ff0000", "{effect}"); + assert_eq!(pixel(&s), drawn, "{effect}"); + } +} + +#[test] +fn a_filter_recolours_the_object_as_one_undo_step() { + let (mut s, id) = red_rect(); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute("addon.color.filter", &json!({"effect": "addon.color.invert"})).unwrap(); + assert_eq!(v["changed"], 1); + assert_eq!(fill_hex(&s, id), "#00ffff"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.appearance.effects.is_empty(), "no effect is added"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_hex(&s, id), "#ff0000"); +} + +#[test] +fn a_filter_takes_any_colour_adjustment_with_its_params() { + let (mut s, id) = red_rect(); + s.execute("addon.color.filter", &json!({"effect": "adjust.hueSaturation", "params": {"hue": 120}})).unwrap(); + assert_eq!(fill_hex(&s, id), "#00ff00"); + // Live effects already on the object stay live, on top of the new colours. + s.execute("effect.apply", &json!({"effect": "addon.color.invert"})).unwrap(); + s.execute("addon.color.filter", &json!({"effect": "addon.color.desaturate", "ids": [id.0]})).unwrap(); + assert_eq!(fill_hex(&s, id), "#808080"); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.effects.len(), 1); + // The stroke only: the fill stays. + s.execute("addon.color.filter", &json!({"effect": "addon.color.invert", "fill": false})).unwrap(); + assert_eq!(fill_hex(&s, id), "#808080"); +} + +#[test] +fn bad_requests_are_refused() { + let (mut s, id) = red_rect(); + let undo = s.doc().unwrap().history.undo.len(); + for p in [ + json!({}), + json!({"effect": 3}), + json!({"effect": "distort.roughen"}), + json!({"effect": "adjust.nothing"}), + json!({"effect": "addon.color.invert", "params": [1]}), + json!({"effect": "addon.color.invert", "ids": [999_999]}), + json!({"effect": "addon.color.invert", "ids": ["x"]}), + ] { + assert!(s.execute("addon.color.filter", &p).is_err(), "{p}"); + } + assert_eq!(fill_hex(&s, id), "#ff0000"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("addon.color.filter", &json!({"effect": "addon.color.invert"})).is_err(), "nothing selected"); +} + +/// An embedded image object of `blob`, selected. +fn image(s: &mut Session, key: &str, blob: vectorcraft_doc::ImageBlob, x: f64) -> NodeId { + s.edit("Place", |d, sel| { + d.images.insert(key.into(), blob); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: key.into(), + width: 4, + height: 4, + xf: vectorcraft_geom::Affine::translate((x, 0.0)) * vectorcraft_geom::Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap() +} + +fn png(img: image::DynamicImage) -> vectorcraft_doc::ImageBlob { + let mut bytes = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + vectorcraft_doc::ImageBlob::png(bytes) +} + +fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.clone() +} + +#[test] +fn select_by_color_kind_finds_spot_colours_effects_and_image_models() { + let (mut s, plain) = red_rect(); + // A spot colour, inside a group: the path is taken, not the group. + s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0.0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap(); + let spot = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"swatch": "Gold"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + // A live colour adjustment. + let adjusted = NodeId(s.execute("shape.rectangle", &json!({"x": 140, "y": 20, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + // Its own colour: setting the spot fill made it the default for new art too. + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("effect.apply", &json!({"effect": "addon.color.invert"})).unwrap(); + let rgb = image(&mut s, "rgb", png(image::DynamicImage::ImageRgb8(image::RgbImage::new(4, 4))), 0.0); + let gray = image(&mut s, "gray", png(image::DynamicImage::ImageLuma8(image::GrayImage::new(4, 4))), 50.0); + let inks = vectorcraft_doc::cmyk::Inks::new(4, 4, vec![0; 64]).unwrap(); + let cmyk = image(&mut s, "cmyk", vectorcraft_doc::ImageBlob::cmyk_tiff(&inks).unwrap(), 100.0); + for (kind, ids) in [ + ("spotColors", vec![spot]), + ("colorEffects", vec![adjusted]), + ("rgbImages", vec![rgb]), + ("grayImages", vec![gray]), + ("cmykImages", vec![cmyk]), + ] { + let v = s.execute("addon.color.select", &json!({"kind": kind})).unwrap(); + assert_eq!((selected(&s), v["count"].clone()), (ids.clone(), json!(ids.len())), "{kind}"); + } + // Locked objects are left out; none found selects nothing. + s.execute("select.set", &json!({"ids": [spot.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!(s.execute("addon.color.select", &json!({"kind": "spotColors"})).unwrap()["count"], 0); + assert!(!selected(&s).contains(&plain)); + assert!(s.execute("addon.color.select", &json!({"kind": "pantone"})).is_err()); + assert!(s.execute("addon.color.select", &json!({})).is_err()); +} + +/// Vector Halftone, the live effect. +const HALFTONE: &str = "addon.color.halftone"; + +/// The dots in group `g`: each path's geometry, ink and blend mode. +fn dots(g: &vectorcraft_doc::Node) -> Vec<(vectorcraft_geom::PathData, String, vectorcraft_color::BlendMode)> { + let ink = |c: &vectorcraft_doc::Node| c.appearance.fill_paint().color().unwrap().to_hex(); + g.children().unwrap().iter().map(|c| (c.path_data().unwrap().clone(), ink(c), c.blend)).collect() +} + +/// `format` as `document.export` writes the active document. +fn exported(s: &mut Session, format: &str) -> Vec { + let v = s.execute("document.export", &json!({"format": format})).unwrap(); + vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap() +} + +/// How many subpaths the path data of `svg` starts. +fn svg_moves(svg: &[u8]) -> usize { + let svg = String::from_utf8_lossy(svg); + svg.split(" d=\"").skip(1).map(|d| d.split('"').next().unwrap_or("").matches(['M', 'm']).count()).sum() +} + +#[test] +fn expand_appearance_gives_the_dots_object_vector_halftone_makes() { + for params in [ + json!({"frequency": 18}), + json!({"frequency": 12, "mode": "cmyk", "shape": "square", "angle": 15}), + json!({"shape": "line", "invert": true, "clip": false}), + json!({"shape": "ellipse", "color": "#336699", "angle": -30}), + ] { + let (mut live, id) = red_rect(); + live.execute("effect.apply", &json!({"effect": HALFTONE, "params": params})).unwrap(); + assert_eq!(fill_hex(&live, id), "#ff0000", "the effect leaves the object as it is"); + live.execute("effect.expandAppearance", &json!({})).unwrap(); + let expanded = live.doc().unwrap().doc.node(id).cloned().unwrap(); + assert!(expanded.appearance.effects.is_empty()); + let (mut made, _) = red_rect(); + let r = made.execute("object.vectorHalftone", ¶ms).unwrap(); + let g = made.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).cloned().unwrap(); + assert!(!dots(&g).is_empty(), "{params}"); + assert_eq!(dots(&expanded), dots(&g), "{params}"); + // Ids of their own. + let ids: std::collections::HashSet<_> = expanded.children().unwrap().iter().map(|c| c.id).chain([id]).collect(); + assert_eq!(ids.len(), expanded.children().unwrap().len() + 1); + } +} + +#[test] +fn exports_write_the_dots_as_paths() { + let (mut s, _) = red_rect(); + let plain: Vec = ["pdf", "eps", "ai"].map(|f| exported(&mut s, f).len()).to_vec(); + s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"frequency": 18}})).unwrap(); + // The exporters' copy of the document has the dots in the object's place. + let baked = vectorcraft_render::effects::bake_document(&s.doc().unwrap().doc).unwrap(); + let mut paths = 0; + baked.walk(|n| { + assert!(n.appearance.effects.iter().all(|e| e.id != HALFTONE)); + paths += n.path_data().map_or(0, |p| p.subpaths.len()); + }); + assert!(paths > 100, "{paths} subpaths"); + // SVG: path data of a subpath per dot. + let moves = svg_moves(&exported(&mut s, "svg")); + assert!(moves > 100, "{moves} subpaths"); + // PDF, EPS and AI: the dots' paths make each file larger. + for (f, plain) in ["pdf", "eps", "ai"].into_iter().zip(plain) { + let with = exported(&mut s, f).len(); + assert!(with > plain + 1000, "{f}: {with} bytes, {plain} without the effect"); + } +} + +#[test] +fn a_halftone_past_the_caps_leaves_the_object_as_it_is() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 9000})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"frequency": 300}})).unwrap(); + // Drawn as it is, exported and expanded without dots and without a panic. + pixel(&s); + assert!(svg_moves(&exported(&mut s, "svg")) < 5); + let r = s.execute("effect.expandAppearance", &json!({})); + assert!(!matches!(r, Err(crate::EngineError::Internal { .. })), "{r:?}"); + let n = s.doc().unwrap().doc.node(id).cloned().unwrap(); + assert!(n.children().is_none_or(|c| c.len() < 5), "no dots"); +} + +/// Duotone, the live effect. +const DUOTONE: &str = "addon.color.duotone"; + +/// A document with spot swatch "Ink" and a selected grey (50 %) rectangle, unstroked. +fn grey_rect() -> (Session, NodeId) { + let (mut s, id) = red_rect(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0.0, "m": 0.6, "y": 1.0, "k": 0.0}, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": {"gray": 0.5}})).unwrap(); + (s, id) +} + +fn ink_tone(curve: &str) -> serde_json::Value { + json!({"tones": [{"color": {"model": "cmyk", "c": 0.0, "m": 0.6, "y": 1.0, "k": 0.0}, "swatch": "Ink", "curve": curve}]}) +} + +fn fill_paint(s: &Session, id: NodeId) -> vectorcraft_color::Paint { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().clone() +} + +#[test] +fn duotone_draws_a_tint_of_its_spot_tone_and_expands_to_it() { + let (mut s, id) = grey_rect(); + let grey = pixel(&s); + s.execute("effect.apply", &json!({"effect": DUOTONE, "params": ink_tone("0,0 100,100")})).unwrap(); + assert_eq!(fill_paint(&s, id).color().unwrap(), vectorcraft_color::Color::gray(0.5), "the colours stay"); + let drawn = pixel(&s); + assert!(drawn != grey && drawn[0] > drawn[2], "drawn in the ink: {drawn:?}"); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill_paint(&s, id) else { panic!("a solid fill") }; + assert_eq!(swatch.as_deref(), Some("Ink"), "linked to the spot swatch, so it separates on its plate"); + assert!((tint - 0.5).abs() < 0.01, "{tint}"); +} + +#[test] +fn duotone_as_a_filter_equals_the_live_effect_expanded() { + for params in [ + ink_tone("0,0 100,100"), + ink_tone("0,0 40,70 100,100"), + json!({"tones": [{"color": "#00ffff", "swatch": "Ink"}, {"color": {"model": "cmyk", "c": 0.0, "m": 0.0, "y": 0.0, "k": 1.0}, "curve": "0,0 100,40"}]}), + json!({"tones": [{"color": "#000000"}], "skipSpot": true}), + ] { + let (mut live, id) = grey_rect(); + live.execute("effect.apply", &json!({"effect": DUOTONE, "params": params})).unwrap(); + live.execute("effect.expandAppearance", &json!({})).unwrap(); + let (mut filtered, _) = grey_rect(); + let undo = filtered.doc().unwrap().history.undo.len(); + assert_eq!(filtered.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": params})).unwrap()["changed"], 1); + assert_eq!(filtered.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(fill_paint(&filtered, id), fill_paint(&live, id), "{params}"); + } + // The params round-trip: the effect keeps what it was given, and the filter reads the same. + let (mut s, id) = grey_rect(); + let params = ink_tone("0,0 40,70 100,100"); + s.execute("effect.apply", &json!({"effect": DUOTONE, "params": params})).unwrap(); + let kept = s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone(); + assert_eq!(kept["tones"], params["tones"]); + s.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": kept})).unwrap(); + let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill_paint(&s, id) else { panic!("a solid fill") }; + assert_eq!(swatch.as_deref(), Some("Ink")); + let fx = vectorcraft_render::effects::addons::duotone::tone_curve_points(Some(&json!("0,0 40,70 100,100"))); + let want = vectorcraft_render::effects::curve_at(&fx, 0.5); + assert!(want > 0.7 && (tint - want).abs() < 0.01, "the curve lifts the mid tone: {tint}, {want}"); +} + +#[test] +fn duotone_skips_spot_colours_when_asked() { + let (mut s, id) = grey_rect(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + let spot = fill_paint(&s, id); + s.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": {"tones": [{"color": "#000000"}], "skipSpot": true}})).unwrap(); + assert_eq!(fill_paint(&s, id), spot); + s.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": {"tones": [{"color": "#000000"}]}})).unwrap(); + assert_ne!(fill_paint(&s, id), spot); +} diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs new file mode 100644 index 0000000000..30548b80a7 --- /dev/null +++ b/crates/engine/src/cmd/addons/document.rs @@ -0,0 +1,230 @@ +//! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of +//! the document named with the date and time through File › Save a Copy's save; New Symbols from +//! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a +//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins › +//! Document Tools) is the UI's. + +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration}; + +use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol}; +use super::super::fileio::{self, SaveMode}; +use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use crate::{Result, Session}; + +/// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken. +const MAX_NUMBER: u32 = 999; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.document.saveTimestampedCopy", + "Save a Timestamped Copy", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder? (default: the document's own folder; needed for a document never saved), format?: vectorcraft|pdf|svg|svgz|ai|eps (default: the document's own, else vectorcraft), time?: Unix seconds (default: now)} write a copy of the document named _YYYY-MM-DD_HH-MM. (the date and time in UTC; -2, -3… added when that name is taken) as File › Save a Copy writes it: the document keeps its path, title and modified state, and no undo step is made. Off where there is no clock (the web) → {path, format, bytes, warnings}", + has_clock, + save_timestamped_copy + ), + cmd!( + "addon.document.exportAllOpen", + "Export All Open Documents", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (.; -2, -3… added when that name is taken, so no file is replaced), one self-contained file each with all of its art (images embedded or included, every artboard; no remembered save options apply): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}", + has_doc, + export_all_open + ), + cmd!( + "addon.document.symbolsFromLayers", + "New Symbols from Layers", + ["Object", "Plug-ins", "Document Tools"], + None, + "{layers?: [layer id…] (top-level layers; default: those highlighted in the Layers panel when two or more are, else every one), replace?: bool (false: the art stays; true: each layer's art is replaced by an instance of its symbol in the same place)} make one symbol of each layer's art as symbol.new makes one (registration in the centre), named after the layer (with a number added when a symbol has that name), as one undo step. Layers with no art are skipped, and with replace so are locked layers; with replace the instances are selected → {symbols: [name…], ids: [instance id…] (with replace), skipped: [{layer, name, reason: \"empty\"|\"locked\"}…]}", + has_doc, + symbols_from_layers + ), + ] +} + +/// A document is open and the time can be told. +fn has_clock(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + vectorcraft_doc::metadata::output_time().map(|_| ()).ok_or_else(|| "there is no clock here".into()) +} + +/// `.`, then `-2.`… in `folder`: the first that `taken` doesn't hold. +fn free_name(folder: &str, base: &str, ext: &str, taken: impl Fn(&str) -> bool) -> Option { + (1..=MAX_NUMBER) + .map(|i| { + let name = if i == 1 { format!("{base}.{ext}") } else { format!("{base}-{i}.{ext}") }; + std::path::Path::new(folder).join(name).to_string_lossy().into_owned() + }) + .find(|path| !taken(path)) +} + +fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.document.saveTimestampedCopy"; + let st = s.doc()?; + let format = match str_param(p, "format") { + Some(f) => fileio::save_format(Some(f), None), + // A document opened from a format Save doesn't write (a picture, a drawing) copies as native. + None => fileio::save_format(Some(st.format), None).or_else(|_| fileio::save_format(None, None)), + } + .map_err(|e| bad(C, e))?; + let folder = match str_param(p, "folder").filter(|f| !f.trim().is_empty()) { + Some(f) => f.to_string(), + None => st + .path + .as_deref() + .and_then(|path| std::path::Path::new(path).parent()) + .map(|f| f.to_string_lossy().into_owned()) + .filter(|f| !f.is_empty()) + .ok_or_else(|| bad(C, "the document has never been saved: give `folder`"))?, + }; + let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&st.doc.title)); + let given = date_param(p, "time", C)?; + let t = clock_date(s, "time", given).ok_or_else(|| bad(C, "there is no clock here: give `time` (Unix seconds)"))?; + let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); + let base = format!("{stem}_{y:04}-{mo:02}-{d:02}_{h:02}-{mi:02}"); + // Only whether something is there: the write itself goes through the automation roots. + let path = free_name(&folder, &base, format.extensions[0], |p| std::path::Path::new(p).exists()) + .ok_or_else(|| bad(C, "every numbered name for the copy is taken"))?; + fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) +} + +/// The save options of every copy, given in full so that no document's remembered options (linked +/// SVG images, a PDF page range, separate artboard files) apply: one self-contained file per +/// document with all of its art. Each format reads only the options it has, and `range` is left +/// out of SVG, where it would pick artboards over `useArtboards`. +fn copy_options(format: &str) -> Value { + match format { + "svg" | "svgz" => json!({ "images": "embed", "useArtboards": false }), + "pdf" => json!({ "range": "all" }), + "eps" => json!({ "includeLinkedFiles": true, "useArtboards": false }), + "ai" | "ait" => json!({ "range": "all", "includeLinked": true, "separateArtboards": false }), + _ => json!({ "includeLinked": true, "separateArtboards": false }), + } +} + +fn export_all_open(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.document.exportAllOpen"; + let format = fileio::save_format(Some(str_param(p, "format").unwrap_or("pdf")), None).map_err(|e| bad(C, e))?; + let folder = str_param(p, "folder").map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "give `folder`"))?.to_string(); + let ext = format.extensions.first().copied().ok_or_else(|| bad(C, "the format has no file extension"))?; + let (mut files, mut failed, mut written) = (vec![], vec![], Vec::::new()); + let active = s.active; + for i in 0..s.docs.len() { + // Each document in turn is the one Save a Copy writes; switching tabs this way leaves every + // document's tool and interaction alone, and the active one comes back below. + s.active = Some(i); + let Ok(st) = s.doc() else { continue }; + let title = st.doc.title.clone(); + let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title)); + // Names the copies already took count as taken, as do files on disk. + let Some(path) = free_name(&folder, &stem, ext, |p| written.iter().any(|w| w == p) || std::path::Path::new(p).exists()) else { + failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" })); + continue; + }; + let options = copy_options(format.id); + match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id, "options": options })) { + Ok(r) => { + written.push(path.clone()); + // Any other file the save wrote is taken for the copies still to come. + for key in ["files", "linked"] { + for f in r.get(key).and_then(Value::as_array).into_iter().flatten() { + if let Some(f) = f.as_str().or_else(|| f.get("path").and_then(Value::as_str)) { + written.push(f.to_string()); + } + } + } + files.push(json!({ "title": title, "path": r.get("path").cloned().unwrap_or(json!(path)), "warnings": r.get("warnings").cloned().unwrap_or(json!([])) })); + } + Err(e) => failed.push(json!({ "title": title, "error": e.to_string() })), + } + } + s.active = active; + Ok(json!({ "files": files, "failed": failed, "format": format.id })) +} + +/// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds +/// no layers). +fn without_layers(n: &Node) -> Node { + let mut n = n.clone(); + if let NodeKind::Layer { children, clip, .. } = &n.kind { + n.kind = NodeKind::Group { children: children.clone(), clip: *clip }; + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| matches!(c.kind, NodeKind::Layer { .. })) { + *c = Arc::new(without_layers(c)); + } + } + n +} + +fn symbols_from_layers(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.document.symbolsFromLayers"; + let replace = switch_or(p, "replace", false, C)?; + let st = s.doc()?; + let d = &st.doc; + let layers: Vec = match p.get("layers").filter(|v| !v.is_null()) { + // The layers highlighted in the Layers panel when two or more are (one is mostly just the + // current layer), else every one. + None => { + let rows = st.highlighted_rows(); + let picked: Vec = d.layers.iter().map(|l| l.id).filter(|id| rows.contains(id)).collect(); + if picked.len() > 1 { picked } else { d.layers.iter().map(|l| l.id).collect() } + } + Some(_) => { + let ids = checked_ids_param(s, p, "layers", C)?; + if let Some(NodeId(id)) = ids.iter().find(|id| !d.layers.iter().any(|l| l.id == **id)) { + return Err(bad(C, format!("{id} is no top-level layer"))); + } + d.layers.iter().map(|l| l.id).filter(|id| ids.contains(id)).collect() + } + }; + // Each layer with art: its id and name, the art's roots, and the art ready for a symbol. + let (mut made, mut skipped) = (vec![], vec![]); + for layer in layers.iter().filter_map(|id| d.layers.iter().find(|l| l.id == *id)) { + let name = layer.display_name(); + let roots: Vec = layer.children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default(); + let art = match layer.children().map(Vec::as_slice).unwrap_or_default() { + [] => None, + [one] => Some(without_layers(one)), + many => Some(without_layers(&Node::group(NodeId(0), many.to_vec()))), + }; + let reason = if replace && layer.locked { Some("locked") } else { None }; + let ready = art.and_then(|mut art| { + crate::cmd::threads::keep_shown_text(d, &mut art); + normalize(art).ok() + }); + match (reason, ready) { + (None, Some(ready)) => made.push((name, roots, ready)), + (reason, _) => skipped.push(json!({ "layer": layer.id.0, "name": name, "reason": reason.unwrap_or("empty") })), + } + } + if made.is_empty() { + return Ok(json!({ "symbols": [], "ids": [], "skipped": skipped })); + } + let (names, ids) = s.edit("New Symbols from Layers", |d, sel| { + let (mut names, mut ids) = (vec![], vec![]); + for (name, roots, (art, size, center)) in &made { + let name = d.unique_symbol_name(name); + store_symbol(d, art, &name, *size); + if replace { + ids.push(instance_in_place(d, roots, &name, place_xf(*center, *size, SymbolRegistration::CENTER))?); + } + names.push(name); + } + if replace { + sel.set(ids.iter().copied()); + } + Ok((names, ids)) + })?; + Ok(json!({ "symbols": names, "ids": ids.iter().map(|i| i.0).collect::>(), "skipped": skipped })) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs new file mode 100644 index 0000000000..562a389e8a --- /dev/null +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -0,0 +1,278 @@ +//! Document Tools' commands: the timestamped copy's name and place with the document left as it +//! was, symbols made of layers, and bad params refused. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +/// 2026-10-05 14:03:00 UTC. +const TIME: i64 = 1_791_208_980; + +/// A new, empty folder of its own for test `name`. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-addon-document-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s +} + +fn stamp(s: &mut Session, p: Value) -> crate::Result { + s.execute("addon.document.saveTimestampedCopy", &p) +} + +#[test] +fn a_timestamped_copy_goes_next_to_the_document_which_stays_as_it_was() { + let dir = folder("next-to"); + let mut s = session(); + let own = dir.join("poster.vectorcraft"); + s.execute("document.save", &json!({"path": own})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let (steps, title) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.title.clone()); + let r = stamp(&mut s, json!({"time": TIME})).unwrap(); + let copy = dir.join("poster_2026-10-05_14-03.vectorcraft"); + assert_eq!(Path::new(r["path"].as_str().unwrap()), copy); + assert!(copy.is_file()); + let st = s.doc().unwrap(); + assert_eq!(st.path.as_deref().map(Path::new), Some(own.as_path()), "the document keeps its path"); + assert_eq!((st.history.undo.len(), &st.doc.title, st.is_dirty()), (steps, &title, true), "no step; still modified"); + // The copy holds the document as it is now: the ellipse too. + let mut other = Session::new(); + other.execute("document.open", &json!({"path": copy})).unwrap(); + assert_eq!(other.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + // The same minute again: numbered. + let r = stamp(&mut s, json!({"time": TIME})).unwrap(); + assert!(r["path"].as_str().unwrap().ends_with("poster_2026-10-05_14-03-2.vectorcraft"), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_unsaved_document_needs_a_folder_and_other_formats_take_their_extension() { + let dir = folder("unsaved"); + let mut s = session(); + let before = s.doc().unwrap().doc.clone(); + assert!(stamp(&mut s, json!({"time": TIME})).is_err(), "no folder to put it in"); + let r = stamp(&mut s, json!({"time": TIME, "folder": dir, "format": "svg"})).unwrap(); + let name = Path::new(r["path"].as_str().unwrap()).file_name().unwrap().to_string_lossy().into_owned(); + assert!(name.ends_with("_2026-10-05_14-03.svg") && dir.join(&name).is_file(), "{name}"); + let st = s.doc().unwrap(); + assert!(st.path.is_none() && *st.doc == *before, "the document is unchanged"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_params_are_refused_and_writes_stay_inside_the_automation_roots() { + let dir = folder("bad"); + let mut s = session(); + for p in [ + json!({"folder": dir, "format": "png"}), + json!({"folder": dir, "format": "dxf"}), + json!({"folder": dir, "time": "now"}), + json!({"folder": dir, "time": 1.5}), + json!({"folder": dir.join("missing").join("deeper"), "time": TIME}), + ] { + assert!(stamp(&mut s, p.clone()).is_err(), "{p}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing written"); + let allowed = dir.join("allowed"); + std::fs::create_dir_all(&allowed).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&dir], &[&allowed]).unwrap(); + let outside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": dir, "time": TIME}))); + assert!(outside.is_err(), "outside the write root"); + let inside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": allowed, "time": TIME}))); + assert!(inside.is_ok(), "{inside:?}"); + assert!(!enabled_without_document(), "off with no document"); + let _ = std::fs::remove_dir_all(&dir); +} + +fn enabled_without_document() -> bool { + Session::new().commands().into_iter().find(|c| c.id == "addon.document.saveTimestampedCopy").unwrap().enabled +} + +fn layer_ids(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().map(|l| l.id.0).collect() +} + +fn symbol_names(s: &Session) -> Vec { + s.doc().unwrap().doc.symbols.iter().map(|x| x.name.clone()).collect() +} + +/// A document of three layers: `Layer 1` with two rectangles, an empty one, and `Icons` with one +/// ellipse. +fn layered() -> Session { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("layer.new", &json!({"name": "Icons"})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 100, "width": 40, "height": 20})).unwrap(); + s +} + +#[test] +fn a_symbol_is_made_of_each_layer_and_empty_layers_are_reported() { + let mut s = layered(); + let before = symbol_names(&s).len(); + let n = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n + 1, "one undo step"); + let names: Vec = serde_json::from_value(r["symbols"].clone()).unwrap(); + assert_eq!(names.len(), 2, "{r}"); + assert!(names.contains(&"Icons".to_string())); + assert_eq!(symbol_names(&s).len(), before + 2); + assert_eq!(r["skipped"].as_array().unwrap().len(), 1, "the empty layer: {r}"); + assert_eq!(r["skipped"][0]["reason"], json!("empty")); + assert_eq!(r["ids"], json!([]), "without replace the art stays"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + // Again: the names are taken, so they get numbers. + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert!(r["symbols"].as_array().unwrap().contains(&json!("Icons 2")), "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(symbol_names(&s).len(), before); +} + +#[test] +fn replace_puts_an_instance_where_the_layers_art_was() { + let mut s = layered(); + let first = layer_ids(&s)[0]; + let bounds = |s: &Session, id: NodeId| s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + let layer = NodeId(first); + let art = bounds(&s, layer); + let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [first], "replace": true})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let inst = NodeId(ids[0].as_u64().unwrap()); + let st = s.doc().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1); + assert!(matches!(&kids[0].kind, NodeKind::SymbolInstance { .. })); + assert_eq!(st.selection.objects, [inst]); + let now = bounds(&s, layer); + assert!((now.x0 - art.x0).abs() < 1e-6 && (now.y1 - art.y1).abs() < 1e-6 && (now.width() - art.width()).abs() < 1e-6, "{art:?} {now:?}"); + assert_eq!(s.doc().unwrap().doc.layers.len(), 3, "the other layers untouched"); +} + +#[test] +fn locked_layers_keep_their_art_and_bad_layers_are_refused() { + let mut s = layered(); + let ids = layer_ids(&s); + s.execute("layer.setProps", &json!({"id": ids[2], "locked": true})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({"replace": true})).unwrap(); + let skipped: Vec<&str> = r["skipped"].as_array().unwrap().iter().map(|k| k["reason"].as_str().unwrap()).collect(); + assert_eq!(skipped, ["empty", "locked"]); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + for p in [json!({"layers": [rect]}), json!({"layers": [u64::MAX]}), json!({"layers": "all"}), json!({"layers": [-1]}), json!({"replace": "yes"})] + { + assert!(s.execute("addon.document.symbolsFromLayers", &p).is_err(), "{p}"); + } + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1); + // Only an empty layer: nothing made, no step. + let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [ids[1]]})).unwrap(); + assert_eq!((r["symbols"].clone(), s.doc().unwrap().history.undo.len()), (json!([]), before.1)); +} + +#[test] +fn the_layers_highlighted_in_the_layers_panel_are_the_default() { + let mut s = layered(); + let ids = layer_ids(&s); + // One highlighted row is just the current layer: every layer. + s.execute("layer.setCurrent", &json!({"id": ids[0]})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!(r["symbols"].as_array().unwrap().len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [ids[1], ids[2]]})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); +} + +/// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be +/// written lists every document in `failed`, and either way the active document stays active. +#[test] +fn export_all_open_documents_writes_each_and_reports_failures() { + let dir = std::env::temp_dir().join(format!("vc-export-all-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "one"})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "two"})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": dir, "format": "svg"})).unwrap(); + assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}"); + assert!(dir.join("one.svg").exists() && dir.join("two.svg").exists()); + assert_eq!(s.active_index(), Some(0)); + assert!(s.documents().iter().all(|d| d.path.is_none()), "the documents stay unsaved"); + let missing = dir.join("missing").join("deeper"); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": missing, "format": "svg"})).unwrap(); + assert_eq!((r["files"].as_array().unwrap().len(), r["failed"].as_array().unwrap().len()), (0, 2), "{r}"); + assert_eq!(s.active_index(), Some(0)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An SVG document last saved with linked images exports as one SVG with its images embedded: no +/// image file is written beside the copies (#4920 review). +#[test] +fn export_all_open_documents_writes_one_file_each() { + let dir = std::env::temp_dir().join(format!("vc-export-all-one-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("out")).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap(); + let mut png = vec![]; + image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap(); + let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect(); + assert!(saved.len() > 1, "the linked save wrote its image beside it: {saved:?}"); + let out = dir.join("out"); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap(); + let names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["pic.svg"], "{r}"); + assert!(std::fs::read_to_string(out.join("pic.svg")).unwrap().contains("data:image/png;base64,"), "the image is embedded"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A PDF document last saved with a page range exports with every page, and an SVG document with +/// two artboards exports as one SVG holding the art of both (#4920 review). +#[test] +fn export_all_open_documents_keeps_every_page_and_artboard() { + let dir = std::env::temp_dir().join(format!("vc-export-all-pages-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("out")).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "name": "pages"})).unwrap(); + s.execute("document.save", &json!({"path": dir.join("pages.pdf"), "format": "pdf", "options": {"range": "1"}})).unwrap(); + let pages = |b: &[u8]| { + String::from_utf8_lossy(b).matches("/Type /Page\n").count() + + String::from_utf8_lossy(b).matches("/Type/Page/").count() + + String::from_utf8_lossy(b).matches("/Type /Page/").count() + + String::from_utf8_lossy(b).matches("/Type /Page ").count() + }; + let first = pages(&std::fs::read(dir.join("pages.pdf")).unwrap()); + let out = dir.join("out"); + s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "pdf"})).unwrap(); + let copy = pages(&std::fs::read(out.join("pages.pdf")).unwrap()); + assert!(copy > first, "the copy has every page: {first} saved, {copy} exported"); + // SVG: one file with the art on both artboards. + let a = s.doc().unwrap().doc.artboards[1].rect; + s.execute("shape.rectangle", &json!({"x": a.x0 + 10.0, "y": a.y0 + 10.0, "width": 20, "height": 20})).unwrap(); + s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap(); + let svgs: Vec = + std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".svg")).collect(); + assert_eq!(svgs, ["pages.svg"]); + let svg = std::fs::read_to_string(out.join("pages.svg")).unwrap(); + // Not the first artboard alone (its 100 × 100 box at the origin): the art's own bounds. + let view = svg.split("viewBox=\"").nth(1).and_then(|v| v.split('"').next()).unwrap(); + let w: f64 = view.split_whitespace().nth(2).unwrap().parse().unwrap(); + assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs new file mode 100644 index 0000000000..5d0e5723ff --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -0,0 +1,902 @@ +//! Path Precision Tools (`addon.pathtools.*`), a built-in add-on: the Anchor Eraser Brush's stroke, +//! the Extend Path tool's extension, the Measure & Inspect tool's readouts, the Anchor Inspector's +//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners +//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's +//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes and Expand Dashes +//! into Paths. +//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's +//! and the UI's. + +mod corners; +#[cfg(test)] +mod effect_tests; +mod shape; +mod shared_edge; +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{AnchorRef, Appearance, AppearanceItem, Document, LineCap, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point, SubPath}; +use vectorcraft_pathops::addons::{self as po, pathtools as pt}; + +use super::super::draw2::{replace_with_pieces, usize_opt}; +use super::super::pathops::Beside; +use super::super::{ + CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, finite_numbers, has_doc, has_selection, number_or, switch_or, text_param, +}; +use crate::{EngineError, Result, Session}; + +/// The Anchor Eraser Brush's tolerance by default (the scale Simplify Anchors (Keep Shape) uses). +const ERASE_TOLERANCE: f64 = 10.0; +/// Most points one brush stroke carries. +const MAX_STROKE_POINTS: usize = 100_000; +/// Most anchors one command edits at once. +const MAX_ANCHORS: usize = 2_000_000; +/// The narrowest a brush gets at the lightest pen pressure (pt). +const MIN_RADIUS: f64 = 0.05; +/// The widest brush (pt). +const MAX_DIAMETER: f64 = 2500.0; +/// The farthest an end is extended at once (pt). +const MAX_EXTEND: f64 = 1e6; +/// Most pieces Divide into Dashes and Expand Dashes into Paths make at once. +const MAX_PIECES: usize = 100_000; +/// Most anchors Add Points puts on each segment. +const MAX_ADD: u64 = pt::MAX_ADDED_PER_SEGMENT as u64; + +pub fn specs() -> Vec { + let mut v = vec![ + cmd!( + "addon.pathtools.erase", + "Anchor Eraser Brush", + [], + None, + "{points: [[x, y] | [x, y, pressure 0..1]…] (the brush's path, at most 100000 points), diameter?: pt 0.1..2500 (20; a point's pressure scales it), tolerance?: 1..100 (10; the outline may move up to tolerance × 0.02 pt), ignoreTolerance?: bool (false: every anchor under the brush that can go goes, its neighbours refitted), plain?: bool (false: true deletes them without refitting the handles beside them), ids?: [id…] (default: the selection)} remove the anchors of the paths under the objects that the brush passes over and that can go while the outline stays within the tolerance, as one undo step; open ends stay → {ids, removed}", + has_selection, + erase + ), + cmd!( + "addon.pathtools.extend", + "Extend Path", + [], + None, + "{id, subpath?: index (0), end: \"start\"|\"end\", length?: pt (negative shortens; never all of it), to?: [x, y] (instead of length: the length that brings the end nearest this point), mode?: \"straight\"|\"bezier\" (stretch the last segment's curve, no anchor added)|\"arc\" (along the circle the end curves on, at most half way round) (\"straight\")} lengthen an open path at an end the way it runs there, or shorten it back along itself, as one undo step; with Keep Shared Points Together on, anchors coincident with an end that moves go with it → {id, length (pt)}", + has_doc, + extend + ), + cmd!( + query "addon.pathtools.inspect", + "Measure & Inspect", + [], + None, + "{id, x, y, tolerance?: pt (3; how near an anchor counts as over it)} what the path reads at the point nearest (x, y): {subpath, closed, anchors, length, area (pt², an open subpath closed by a straight line), segment, t, point: [x, y], segmentLength, tangent (degrees counter-clockwise), radius (of curvature, null where straight), anchor?: {index, x, y, smooth, angle (at the anchor, null at an open end), in?: {length, angle}, out?: {length, angle}}}", + has_doc, + inspect + ), + cmd!( + "addon.pathtools.setAnchor", + "Set Anchor", + [], + None, + "{x?, y?: pt (on the page), inLength?, outLength?: pt (0 retracts), inAngle?, outAngle?: degrees counter-clockwise} move the selected anchors (with their handles) and set their handles, as one undo step: direct-selected anchors, or every anchor of a path selected whole; a smooth anchor's other handle turns with the one set; with Keep Shared Points Together on, anchors coincident with one that moves go with it → {anchors}", + has_selection, + set_anchor + ), + cmd!( + "addon.pathtools.smooth", + "Make Smooth", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ratio?: 0.1..0.5 (0.3905: a square's corners make a circle)} make the selected anchors smooth: a lone handle is mirrored; without handles, both stand at right angles to the bisector of the angle at the anchor, ratio × the nearer neighbour's distance long; two handles are put in line; an open end without handles aims at its neighbour's handle. One undo step → {anchors (changed)}", + has_selection, + smooth + ), + cmd!( + "addon.pathtools.corner", + "Make Corner", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{retract?: bool (true: the handles go; false: they stay where they are and move apart)} make the selected anchors corners, as one undo step → {anchors (changed)}", + has_selection, + corner + ), + cmd!( + "addon.pathtools.equalize", + "Equalize Handles", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} give each selected anchor's two handles their average length (a missing one is made opposite the other), as one undo step → {anchors (changed)}", + has_selection, + equalize + ), + cmd!( + "addon.pathtools.removeKeepShape", + "Remove Points, Keep Shape", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} remove the direct-selected anchors, refitting the handles beside each so the outline keeps its shape as best it can, as one undo step; open ends stay → {removed}", + has_selection, + remove_keep_shape + ), + cmd!( + "addon.pathtools.addPoints", + "Add Points to Segments…", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{count?: 1..100 (1)} add count anchors to each selected segment (a segment between two selected anchors, or every segment of a path selected whole), splitting it into pieces of equal length; the shape doesn't change. One undo step → {added}", + has_selection, + add_points + ), + cmd!( + "addon.pathtools.close", + "Close Path", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{mode?: \"handles\" (keep the ends' handles)|\"straight\" (a straight closing segment)|\"smooth\" (the ends made smooth), ratio?: 0.1..0.5 (0.3905, for smooth)} close the open subpaths of the selected paths, as one undo step → {closed}", + has_selection, + close + ), + cmd!( + "addon.pathtools.crossings", + "Add Points at Crossings", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}", + has_selection, + crossings + ), + cmd!( + "addon.pathtools.slideAnchor", + "Slide Anchor Along Path", + [], + None, + "{id, subpath?: index (0), anchor: index, t: -0.98..0.98 (where to: positive, a curve parameter on the segment after the anchor; negative, back from the end of the one before)} move an anchor along its path, the segments beside it refitted so the outline stays, as one undo step; ends of open paths don't slide; with Keep Shared Points Together on, anchors coincident with it go with it → {id, strayed (pt)}", + has_doc, + slide_anchor + ), + cmd!( + "addon.pathtools.divideDashes", + "Divide into Dashes", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{dash?: pt 0.01..1000000 (10), gap?: pt 0..1000000 (0: the pieces touch), fit?: bool (false: exact lengths, the last piece of each run what is left; true: fit to corners and ends, every run between corners and ends holding whole dashes, all stretched or squeezed alike so it starts and ends on a dash), removeGaps?: bool (true: the gaps are left empty; false: they stay as pieces too)} cut the selected paths into separate open paths along the curve, each dash long with gap between them and keeping the path's appearance, as one undo step. Only the direct-selected segments (or those between two direct-selected anchors) are divided when there are any, the dash pattern running on across segments that follow one another; the rest of such a path stays, as pieces of its own. The pieces are selected; at most 100000 → {ids, dashes}", + has_selection, + divide_dashes + ), + cmd!( + "addon.pathtools.expandDashes", + "Expand Dashes into Paths", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ids?: [id…] (default: the selection)} turn the dashed stroke of each path and compound path under the objects into separate open paths, one per dash, laid out as the stroke draws them (its dash pattern, offset and Align Dashes to Corners and Path Ends), each keeping the path's appearance with the dashes off, so the gaps are real gaps: a dash running all the way round a closed path stays closed, and with a round or projecting cap a dash of no length (a dot) becomes a path on its point. The top stroke's dashes are the ones expanded; its arrowheads go, and the path's fills stay on it, below its dashes. Paths without a dashed stroke stay as they are. One undo step; the dashes are selected; at most 100000 → {ids, dashes}", + has_selection, + expand_dashes + ), + ]; + v.extend(shape::specs()); + v.extend(corners::specs()); + v.extend(shared_edge::specs()); + v +} + +/// The editable paths (not guides) under `roots`, compound path members included. +fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { + let editable = d.editable(); + let mut out = vec![]; + for n in roots.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { guide: false, .. }) && editable(c.id) { + out.push(c.id); + } + }); + } + out +} + +/// Put `np` in path `id`'s place; its live shape goes (its anchors are edited). +fn set_path(d: &mut Document, id: NodeId, np: PathData) { + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = np; + *live = None; + } +} + +/// Error unless the paths together have at most [`MAX_ANCHORS`] anchors. +fn check_size<'a>(paths: impl IntoIterator, cmd: &str) -> Result<()> { + if paths.into_iter().map(PathData::anchor_count).sum::() > MAX_ANCHORS { + return Err(bad(cmd, "the paths have too many anchors to edit at once")); + } + Ok(()) +} + +// ---------- Anchor Eraser Brush ---------- + +/// The brush's points (with the radius each has), from `points`. +fn stroke(p: &Value, radius: f64, cmd: &str) -> Result> { + let list = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must be a list of [x, y] points"))?; + if list.len() > MAX_STROKE_POINTS { + return Err(bad(cmd, "too many `points` (at most 100000)")); + } + list.iter() + .map(|v| { + let point = |[x, y]: [f64; 2], pressure: f64| (Point::new(x, y), (radius * pressure.clamp(0.0, 1.0)).max(MIN_RADIUS)); + finite_numbers::<2>(v) + .map(|xy| point(xy, 1.0)) + .or_else(|| finite_numbers::<3>(v).map(|[x, y, f]| point([x, y], f))) + .ok_or_else(|| bad(cmd, format!("bad point {v}: expected [x, y] or [x, y, pressure]"))) + }) + .collect() +} + +/// Does the brush, sweeping through `pts`, cover `q`? +fn under_brush(pts: &[(Point, f64)], q: Point) -> bool { + let hit = |(a, ra): (Point, f64), (b, rb): (Point, f64)| { + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((q - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + q.distance(a + ab * t) <= ra + (rb - ra) * t + }; + match pts { + [only] => hit(*only, *only), + _ => pts.windows(2).any(|w| matches!(w, [a, b] if hit(*a, *b))), + } +} + +/// The anchors of `sp` that go when the brush passes over those marked, removed without refitting +/// the handles beside them: open ends stay, and the subpath keeps two anchors (three closed). +fn delete_marked(sp: &SubPath, marked: &[bool]) -> SubPath { + let n = sp.anchors.len(); + let min = if sp.closed { 3 } else { 2 }; + let mut left = n.saturating_sub(min); + let mut out = sp.clone(); + let keep: Vec = (0..n) + .map(|i| { + let end = !sp.closed && (i == 0 || i + 1 == n); + let go = !end && left > 0 && marked.get(i).copied().unwrap_or(false); + left -= usize::from(go); + !go + }) + .collect(); + let mut it = keep.iter(); + out.anchors.retain(|_| it.next().copied().unwrap_or(true)); + out +} + +fn erase(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.erase"; + let diameter = number_or(p, "diameter", 20.0, C)?; + if !(0.1..=MAX_DIAMETER).contains(&diameter) { + return Err(bad(C, "`diameter` must be from 0.1 to 2500 pt")); + } + let tolerance = number_or(p, "tolerance", ERASE_TOLERANCE, C)?; + if !(1.0..=100.0).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 1 to 100")); + } + let (ignore, plain) = (switch_or(p, "ignoreTolerance", false, C)?, switch_or(p, "plain", false, C)?); + let pts = stroke(p, diameter / 2.0, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect(); + check_size(paths.iter().map(|(_, p)| *p), C)?; + let tol = if ignore { f64::INFINITY } else { tolerance * po::PT_PER_TOLERANCE }; + let mut removed = 0; + let mut changed = vec![]; + for (id, path) in paths { + let subs: Vec = path + .subpaths + .iter() + .map(|sp| { + let marked: Vec = sp.anchors.iter().map(|a| !pts.is_empty() && under_brush(&pts, a.p)).collect(); + match marked.contains(&true) { + false => sp.clone(), + true if plain => delete_marked(sp, &marked), + true => po::simplify_anchors_keep_shape(sp, tol, &marked), + } + }) + .collect(); + let np = PathData::new(subs); + if np != *path { + removed += path.anchor_count().saturating_sub(np.anchor_count()); + changed.push((id, np)); + } + } + edit_whole(s, "Anchor Eraser Brush", changed)?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "removed": removed })) +} + +/// Replace paths with the new data given, as one step (none when there is nothing to change); each +/// is selected whole, as its anchors' indexes changed. +fn edit_whole(s: &mut Session, label: &str, changed: Vec<(NodeId, PathData)>) -> Result<()> { + if changed.is_empty() { + return Ok(()); + } + s.edit(label, |d, sel| { + for (id, np) in changed { + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + } + Ok(()) + }) +} + +// ---------- Extend Path ---------- + +/// The subpath a request names: (path id, subpath index, its data). +fn named_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, SubPath)> { + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), cmd)?; + let si = usize_opt(p, "subpath", cmd)?.unwrap_or(0); + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(cmd, "the path is locked or hidden")); + } + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(cmd, "`id` is not a path"))?; + let sp = path.subpaths.get(si).ok_or_else(|| bad(cmd, "no such subpath"))?; + Ok((id, si, sp.clone())) +} + +/// Put `new` in place of the subpath `old` (from [`named_subpath`]) as one step labelled `label` +/// (none when it is the same), with what Keep Shared Points Together moves too; the path's direct +/// selection goes. +fn set_subpath(s: &mut Session, label: &str, (id, si, old): (NodeId, usize, SubPath), new: SubPath) -> Result<()> { + if new == old { + return Ok(()); + } + let mut np = s.doc()?.doc.node(id).and_then(|n| n.path_data()).cloned().ok_or(EngineError::NoNode(id))?; + if let Some(slot) = np.subpaths.get_mut(si) { + *slot = new; + } + let shared = shared_edge::shared_points(s, [(id, &np)])?; + s.edit(label, |d, sel| { + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + shared_edge::move_shared(d, shared); + Ok(()) + }) +} + +fn extend(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.extend"; + let (id, si, sp) = named_subpath(s, p, C)?; + if sp.closed || sp.anchors.len() < 2 { + return Err(bad(C, "the subpath has no ends to extend (it is closed or a single point)")); + } + let at_start = match text_param(p, "end", C)? { + Some("start") => true, + Some("end") => false, + _ => return Err(bad(C, "`end` must be \"start\" or \"end\"")), + }; + let mode = match text_param(p, "mode", C)? { + None => pt::ExtendMode::Straight, + Some(m) => pt::ExtendMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"straight\", \"bezier\" or \"arc\""))?, + }; + let length = match (p.get("to").filter(|v| !v.is_null()), p.get("length").filter(|v| !v.is_null())) { + (Some(to), None) => { + let [x, y] = finite_numbers::<2>(to).ok_or_else(|| bad(C, "`to` must be [x, y]"))?; + pt::extend_length_to(&sp, at_start, Point::new(x, y), mode).ok_or_else(|| bad(C, "the path can't be extended"))? + } + (None, Some(_)) => number_or(p, "length", 0.0, C)?, + _ => return Err(bad(C, "give `length` or `to`")), + }; + if !length.is_finite() || length.abs() > MAX_EXTEND { + return Err(bad(C, "`length` must be a number of at most 1000000 pt either way")); + } + let new = pt::extend_open(&sp, at_start, length, mode).ok_or_else(|| bad(C, "the path is too short to shorten that much"))?; + set_subpath(s, "Extend Path", (id, si, sp), new)?; + Ok(json!({ "id": id.0, "length": length })) +} + +// ---------- Slide Anchor Along Path ---------- + +fn slide_anchor(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.slideAnchor"; + let (id, si, sp) = named_subpath(s, p, C)?; + let anchor = usize_opt(p, "anchor", C)?.ok_or_else(|| bad(C, "give `anchor`, the index of the anchor to slide"))?; + let t = number_or(p, "t", f64::NAN, C)?; + if t.is_nan() || t.abs() > pt::MAX_SLIDE { + return Err(bad(C, "`t` must be a number from -0.98 to 0.98")); + } + let (new, strayed) = + pt::slide_anchor(&sp, anchor, t).ok_or_else(|| bad(C, "that anchor can't slide: an end of an open path has nowhere to go"))?; + set_subpath(s, "Slide Anchor Along Path", (id, si, sp), new)?; + Ok(json!({ "id": id.0, "strayed": strayed })) +} + +// ---------- Measure & Inspect ---------- + +fn polar(h: Option<(f64, f64)>) -> Value { + h.map_or(Value::Null, |(length, angle)| json!({ "length": length, "angle": angle })) +} + +fn inspect(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.inspect"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let (x, y) = (number_or(p, "x", f64::NAN, C)?, number_or(p, "y", f64::NAN, C)?); + let tolerance = number_or(p, "tolerance", 3.0, C)?; + if !(x.is_finite() && y.is_finite() && tolerance >= 0.0 && tolerance.is_finite()) { + return Err(bad(C, "give `x` and `y` (and a `tolerance` of 0 or more)")); + } + let path = s.doc()?.doc.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?; + let i = pt::inspect(path, Point::new(x, y), tolerance).ok_or_else(|| bad(C, "the path has no segments to measure"))?; + let anchor = i.anchor.map(|a| { + json!({ "index": a.index, "x": a.p.x, "y": a.p.y, "smooth": a.smooth, "angle": a.angle, "in": polar(a.handle_in), "out": polar(a.handle_out) }) + }); + Ok(json!({ + "subpath": i.subpath, "closed": i.closed, "anchors": i.anchors, "length": i.length, "area": i.area, + "segment": i.segment, "t": i.t, "point": [i.point.x, i.point.y], "segmentLength": i.segment_length, + "tangent": i.tangent, "radius": i.radius, "anchor": anchor, + })) +} + +// ---------- Anchor Inspector ---------- + +/// The anchors the Anchor Inspector acts on, per path: each path's direct-selected anchors, or +/// every anchor of a path selected whole (with `whole`), keyed by subpath. +type Picked = Vec<(NodeId, BTreeMap>)>; + +/// The selected anchors ([`Picked`]); `whole` counts the anchors of paths selected whole. +fn picked_anchors(s: &Session, whole: bool) -> Result { + let st = s.doc()?; + let (d, sel) = (&st.doc, &st.selection); + let roots = super::super::edit::selected_roots(s)?; + let mut out = vec![]; + for id in paths_under(d, &roots) { + let Some(path) = d.node(id).and_then(|n| n.path_data()) else { continue }; + let refs: Vec = match sel.anchors.get(&id).filter(|a| !a.is_empty()) { + Some(set) => set.iter().copied().collect(), + None if whole => path.anchors().map(|(si, ai, _)| (si, ai)).collect(), + None => continue, + }; + let mut by_sub: BTreeMap> = BTreeMap::new(); + for (si, ai) in refs.into_iter().filter(|(si, ai)| path.subpaths.get(*si).is_some_and(|sp| *ai < sp.anchors.len())) { + by_sub.entry(si).or_default().insert(ai); + } + if !by_sub.is_empty() { + out.push((id, by_sub)); + } + } + Ok(out) +} + +/// Edit each selected anchor ([`picked_anchors`]) in place with `f` (true when it changed one), as +/// one step labelled `label`; the selection stays. → how many anchors changed. +fn edit_anchors(s: &mut Session, label: &str, cmd: &str, f: impl Fn(&mut SubPath, usize) -> bool) -> Result { + let picked = picked_anchors(s, true)?; + if picked.is_empty() { + return Err(bad(cmd, "select paths or anchor points")); + } + let d = &s.doc()?.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), cmd)?; + let mut count = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(mut np) = d.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; + let before = count; + for (si, anchors) in by_sub { + let Some(sp) = np.subpaths.get_mut(*si) else { continue }; + count += anchors.iter().filter(|&&i| f(sp, i)).count(); + } + if count > before { + changed.push((*id, np)); + } + } + if !changed.is_empty() { + let shared = shared_edge::shared_points(s, changed.iter().map(|(id, np)| (*id, np)))?; + s.edit(label, |d, _| { + for (id, np) in changed { + set_path(d, id, np); + } + shared_edge::move_shared(d, shared); + Ok(()) + })?; + } + Ok(count) +} + +/// A smoothing `ratio` param (default [`pt::SMOOTH_RATIO`]). +pub(super) fn ratio(p: &Value, cmd: &str) -> Result { + let r = number_or(p, "ratio", pt::SMOOTH_RATIO, cmd)?; + let (lo, hi) = pt::SMOOTH_RATIO_RANGE; + if !(lo..=hi).contains(&r) { + return Err(bad(cmd, "`ratio` must be from 0.1 to 0.5")); + } + Ok(r) +} + +fn smooth(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.smooth"; + let r = ratio(p, C)?; + let n = edit_anchors(s, "Make Smooth", C, |sp, i| pt::auto_smooth(sp, i, r))?; + Ok(json!({ "anchors": n })) +} + +fn corner(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.corner"; + let retract = switch_or(p, "retract", true, C)?; + let n = edit_anchors(s, "Make Corner", C, |sp, i| pt::make_corner(sp, i, retract))?; + Ok(json!({ "anchors": n })) +} + +fn equalize(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.pathtools.equalize"; + let n = edit_anchors(s, "Equalize Handles", C, pt::equalize_handles)?; + Ok(json!({ "anchors": n })) +} + +/// A number param that is given, finite, and (with `range`) inside it. +fn given(p: &Value, key: &str, range: Option<(f64, f64)>, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?; + match range { + Some((lo, hi)) if !(lo..=hi).contains(&x) => Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))), + _ => Ok(Some(x)), + } + } + } +} + +fn set_anchor(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.setAnchor"; + const LIMIT: Option<(f64, f64)> = Some((-1e7, 1e7)); + let (x, y) = (given(p, "x", LIMIT, C)?, given(p, "y", LIMIT, C)?); + let lengths = [given(p, "inLength", Some((0.0, 1e7)), C)?, given(p, "outLength", Some((0.0, 1e7)), C)?]; + let angles = [given(p, "inAngle", LIMIT, C)?, given(p, "outAngle", LIMIT, C)?]; + if [x, y].iter().chain(&lengths).chain(&angles).all(Option::is_none) { + return Err(bad(C, "give x, y, or a handle's length or angle")); + } + let n = edit_anchors(s, "Set Anchor", C, |sp, i| { + let Some(a) = sp.anchors.get_mut(i) else { return false }; + let before = *a; + let to = Point::new(x.unwrap_or(a.p.x), y.unwrap_or(a.p.y)); + a.translate(to - a.p); + for (out, (len, ang)) in [false, true].into_iter().zip(lengths.into_iter().zip(angles)) { + if len.is_none() && ang.is_none() { + continue; + } + let h = if out { a.h_out } else { a.h_in }; + let (l0, a0) = pt::handle_polar(a.p, h).unwrap_or((0.0, if out { 0.0 } else { 180.0 })); + let (l, deg) = (len.unwrap_or(l0), ang.unwrap_or(a0)); + // A length alone keeps a smooth anchor's other handle where it is; an angle turns it too. + let other = if out { a.h_in } else { a.h_out }; + a.set_handle(out, pt::handle_at(a.p, l, deg), false); + if ang.is_none() { + if out { a.h_in = other } else { a.h_out = other } + } + } + *a != before + })?; + Ok(json!({ "anchors": n })) +} + +fn remove_keep_shape(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.pathtools.removeKeepShape"; + let picked = picked_anchors(s, false)?; + if picked.is_empty() { + return Err(bad(C, "direct-select the anchor points to remove")); + } + let d = &s.doc()?.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let mut removed = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(mut np) = d.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; + for (si, anchors) in by_sub { + let Some(sp) = np.subpaths.get_mut(*si) else { continue }; + // From the last back, so the indexes left stay right. + for &i in anchors.iter().rev() { + if let Some((out, _)) = po::remove_anchor_keep_shape(sp, i) { + *sp = out; + removed += 1; + } + } + } + if np != *d.node(*id).and_then(|n| n.path_data()).ok_or(EngineError::NoNode(*id))? { + changed.push((*id, np)); + } + } + edit_whole(s, "Remove Points, Keep Shape", changed)?; + Ok(json!({ "removed": removed })) +} + +/// The segments of subpath `si` (`sp`) picked: the direct-selected segments `segments` of its +/// path, else those between two of its selected `anchors`. +fn picked_segments(segments: Option<&BTreeSet<(usize, usize)>>, si: usize, sp: &SubPath, anchors: &BTreeSet) -> BTreeSet { + let n = sp.anchors.len().max(1); + match segments.filter(|set| !set.is_empty()) { + Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(), + None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n))).collect(), + } +} + +fn add_points(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.addPoints"; + let count = number_or(p, "count", 1.0, C)?; + if !(1.0..=MAX_ADD as f64).contains(&count) || count.fract() != 0.0 { + return Err(bad(C, "`count` must be a whole number from 1 to 100")); + } + let picked = picked_anchors(s, true)?; + let st = s.doc()?; + let d = &st.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let mut added = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue }; + let mut np = path.clone(); + for (si, sp) in np.subpaths.iter_mut().enumerate() { + let Some(anchors) = by_sub.get(&si) else { continue }; + let segs = picked_segments(st.selection.segments.get(id), si, sp, anchors); + let (out, marks) = pt::add_points(sp, Some(&segs), count as usize); + added += marks.len(); + *sp = out; + } + if np != *path { + changed.push((*id, np)); + } + } + if added == 0 { + return Err(bad(C, "select segments, or paths, to add points to")); + } + edit_whole(s, "Add Points to Segments", changed)?; + Ok(json!({ "added": added })) +} + +pub(super) fn close(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.close"; + let mode = match text_param(p, "mode", C)? { + None => pt::CloseMode::Handles, + Some(m) => pt::CloseMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"handles\", \"straight\" or \"smooth\""))?, + }; + let r = ratio(p, C)?; + let roots = super::super::edit::selected_roots(s)?; + let d = &s.doc()?.doc; + let mut closed = 0; + let mut changed = vec![]; + for id in paths_under(d, &roots) { + let Some(path) = d.node(id).and_then(|n| n.path_data()) else { continue }; + let mut np = path.clone(); + let n = np.subpaths.iter_mut().map(|sp| pt::close(sp, mode, r)).filter(|c| *c).count(); + if n > 0 { + closed += n; + changed.push((id, np)); + } + } + if changed.is_empty() { + return Err(bad(C, "select open paths to close")); + } + s.edit("Close Path", |d, _| { + for (id, np) in changed { + set_path(d, id, np); + } + Ok(()) + })?; + Ok(json!({ "closed": closed })) +} + +// ---------- Split / Add Points at Crossings ---------- + +fn crossings(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.crossings"; + let (cut, self_crossings) = (switch_or(p, "cut", false, C)?, switch_or(p, "selfCrossings", false, C)?); + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<&PathData> = ids.iter().filter_map(|id| d.node(*id)?.path_data()).collect(); + if paths.len() != ids.len() { + return Err(EngineError::Other("Add Points at Crossings: a path went missing".into())); + } + let places = pt::crossings(&paths, self_crossings) + .ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross (at most 10000 segments)"))?; + let mut count = 0; + // Each path that is crossed: its new subpaths, and the anchors at the crossings on each. + let mut changed: Vec<(NodeId, Vec, Vec>)> = vec![]; + for ((id, path), on) in ids.iter().zip(&paths).zip(places) { + if on.is_empty() { + continue; + } + let mut subs = vec![]; + let mut marks = vec![]; + for (si, sp) in path.subpaths.iter().enumerate() { + let here: Vec<(usize, f64)> = on.iter().filter(|(s, ..)| *s == si).map(|&(_, seg, t)| (seg, t)).collect(); + let (out, m) = pt::insert_at(sp, &here); + count += m.len(); + subs.push(out); + marks.push(m); + } + changed.push((*id, subs, marks)); + } + if changed.is_empty() { + return Ok(json!({ "ids": [], "crossings": 0 })); + } + let label = if cut { "Split at Crossings" } else { "Add Points at Crossings" }; + let out = s.edit(label, |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, ..)| *id).collect::>()); + for (id, subs, marks) in changed { + sel.anchors.remove(&id); + sel.segments.remove(&id); + if !cut { + set_path(d, id, PathData::new(subs)); + all.push(id); + continue; + } + let pieces: Vec = subs.iter().zip(&marks).flat_map(|(sp, m)| sp.cut_at(m)).collect(); + // A path of one subpath becomes a path per piece; a compound shape's pieces stay its subpaths. + if subs.len() == 1 { + let made = replace_with_pieces(d, &mut beside, id, pieces.into_iter().map(PathData::single).collect())?; + for n in &made { + if !sel.contains(*n) { + sel.add(*n); + } + } + all.extend(made); + } else { + set_path(d, id, PathData::new(pieces)); + all.push(id); + } + } + beside.finish(d)?; + Ok(all) + })?; + Ok(json!({ "ids": out.iter().map(|i| i.0).collect::>(), "crossings": count })) +} + +// ---------- Divide into Dashes ---------- + +fn divide_dashes(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.divideDashes"; + let spec = pt::DashSpec { + dash: given(p, "dash", Some((0.01, 1e6)), C)?.unwrap_or(10.0), + gap: given(p, "gap", Some((0.0, 1e6)), C)?.unwrap_or(0.0), + fit: switch_or(p, "fit", false, C)?, + }; + let remove_gaps = switch_or(p, "removeGaps", true, C)?; + let picked = picked_anchors(s, true)?; + let st = s.doc()?; + let d = &st.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let (mut made, mut dashes) = (0, 0); + // Each path divided: what stays of it (the subpaths not divided, as one path) and its pieces. + let mut changed: Vec<(NodeId, Vec)> = vec![]; + for (id, by_sub) in &picked { + let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue }; + let (mut kept, mut pieces) = (vec![], vec![]); + for (si, sp) in path.subpaths.iter().enumerate() { + let segs = by_sub.get(&si).map(|anchors| picked_segments(st.selection.segments.get(id), si, sp, anchors)).unwrap_or_default(); + if segs.is_empty() { + kept.push(sp.clone()); + continue; + } + let only = (segs.len() < sp.segment_count()).then_some(&segs); + let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made)) + .ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?; + made += out.len(); + for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) { + dashes += usize::from(kind == pt::Piece::Dash); + pieces.push(PathData::single(piece)); + } + } + if !pieces.is_empty() { + changed.push((*id, (!kept.is_empty()).then(|| PathData::new(kept)).into_iter().chain(pieces).collect())); + } + } + if changed.is_empty() { + return Err(bad(C, "select paths, or segments, to divide")); + } + let ids = s.edit("Divide into Dashes", |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::>()); + for (id, pieces) in changed { + all.extend(replace_with_pieces(d, &mut beside, id, pieces)?); + } + beside.finish(d)?; + // The pieces join the objects selected (whole, in one go: there may be many). + let before = std::mem::take(&mut sel.objects); + sel.set(before.into_iter().chain(all.iter().copied())); + Ok(all) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "dashes": dashes })) +} + +// ---------- Expand Dashes into Paths ---------- + +/// The paths and compound paths under `roots` whose top stroke is dashed: a compound path's +/// members stand for it, which holds their paint. Clipping paths are left alone. +fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec { + let editable = d.editable(); + let mut seen = BTreeSet::new(); + let mut out = vec![]; + for id in paths_under(d, roots) { + let compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + let Some(n) = compound.or_else(|| d.node(id)) else { continue }; + let dashed = n.appearance.stroke().and_then(|st| st.dash.as_ref()).is_some_and(|dash| dash.is_dashed()); + if dashed && !matches!(n.kind, NodeKind::Path { clipping: true, .. }) && editable(n.id) && seen.insert(n.id) { + out.push(n.id); + } + } + out +} + +fn expand_dashes(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.expandDashes"; + let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer"); + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + // Each dashed path and its dashes, as the canvas draws them. + let mut changed: Vec<(NodeId, Vec)> = vec![]; + let mut count = 0; + for id in dashed_paths(d, &roots) { + let Some(n) = d.node(id) else { continue }; + let (Some(st), Some(bp)) = (n.appearance.stroke(), n.stroke_path()) else { continue }; + let Some(dash) = &st.dash else { continue }; + // The line the stroke draws: the path, its ends trimmed under any arrowheads. + let line = vectorcraft_render::effects::stroke::stroke_pieces(&bp, st).line; + // A pattern too fine to draw is drawn solid: it has too many dashes to expand. + let dashed = vectorcraft_render::effects::stroke::dash(&line, dash).ok_or_else(too_many)?; + let mut pieces = PathData::from_bezpath(&dashed.path).subpaths; + // A dot paints its cap; a path that stays on its point is drawn so too. Under a butt cap it + // paints nothing. + if st.cap != LineCap::Butt { + pieces.extend(dashed.dots.iter().map(|dot| SubPath::polyline(&[dot.at, dot.at], false))); + } + count += pieces.len(); + if count > MAX_PIECES { + return Err(too_many()); + } + if !pieces.is_empty() { + changed.push((id, pieces)); + } + } + if changed.is_empty() { + return Err(bad(C, "select paths with dashed strokes to expand")); + } + let ids = s.edit("Expand Dashes into Paths", |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::>()); + for (id, pieces) in changed { + let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &n.kind else { continue }; + let rule = *rule; + let filled = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()); + // The dashes: open paths with the strokes (the top one's dashes and arrowheads off). + let mut look = Appearance::clone(&n.appearance); + look.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + if let Some(st) = look.stroke_mut() { + (st.dash, st.start_arrow, st.end_arrow) = (None, None, None); + } + let mut dash = n.clone(); + dash.kind = NodeKind::Path { path: PathData::default(), rule, live: None, clipping: false, guide: false }; + dash.appearance = look.into(); + // The fills stay on the path, below its dashes; without fills it goes. + let mut parts = vec![]; + if n.appearance.items.iter().any(filled) { + let mut fill = n.clone(); + let mut look = Appearance::clone(&n.appearance); + look.items.retain(filled); + fill.appearance = look.into(); + parts.push(fill); + } + for sp in pieces { + let mut piece = d.reid(&dash); + if let NodeKind::Path { path, .. } = &mut piece.kind { + *path = PathData::single(sp); + } + all.push(piece.id); + parts.push(piece); + } + beside.put(d, id, parts)?; + } + beside.finish(d)?; + // The dashes join the objects selected (whole, in one go: there may be many). + let before = std::mem::take(&mut sel.objects); + sel.set(before.into_iter().filter(|id| d.node(*id).is_some()).chain(all.iter().copied())); + Ok(all) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "dashes": ids.len() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/corners.rs b/crates/engine/src/cmd/addons/pathtools/corners.rs new file mode 100644 index 0000000000..464fa032ba --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/corners.rs @@ -0,0 +1,144 @@ +//! The Corner Tool's commands: the app's Live Corners ([`LiveCorners`]) cut, resized and removed on +//! chosen anchors, each edit one undo step. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveCorners, NodeId, NodeKind}; +use vectorcraft_geom::shapes::CornerKind; +use vectorcraft_tools::addons::corner_tool::MAX_RADIUS; + +use super::super::super::object::recut; +use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, number_or}; +use super::{check_size, paths_under}; +use crate::{Result, Session}; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.cornerSet", + "Set Corners", + [], + None, + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", + has_doc, + corner_set + ), + cmd!( + "addon.pathtools.cornerRemove", + "Remove Corners", + [], + None, + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors)} make those live corners sharp again, as one undo step → {ids, corners (how many)}", + has_doc, + corner_remove + ), + ] +} + +/// The `anchors` of `p`. +fn anchors_param(p: &Value, cmd: &str) -> Result>> { + let Some(v) = p.get("anchors").filter(|v| !v.is_null()) else { return Ok(None) }; + let list = v.as_array().ok_or_else(|| bad(cmd, format!("`anchors` must list anchor indices (0, 1, 2…), not {v}")))?; + list.iter() + .map(|k| { + k.as_u64() + .and_then(|k| usize::try_from(k).ok()) + .ok_or_else(|| bad(cmd, format!("`anchors` must list anchor indices (0, 1, 2…), not {k}"))) + }) + .collect::>() + .map(Some) +} + +/// The corners a request names: each path with the corners (anchor indices of its uncut outline). +fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result)>> { + let shared = anchors_param(p, cmd)?; + // Each path with its own `anchors`, or sharing the request's. + let mut own: Vec>> = vec![]; + let ids: Vec = match p.get("items").filter(|v| !v.is_null()) { + None => paths_under(&s.doc()?.doc, &checked_ids_or_selection(s, p, cmd)?), + Some(Value::Array(items)) => { + let mut ids = vec![]; + for it in items { + ids.push(checked_id(s, it.get("id").unwrap_or(&Value::Null), cmd)?); + own.push(anchors_param(it, cmd)?); + } + ids + } + Some(v) => return Err(bad(cmd, format!("`items` must be a list of {{id, anchors?}}, not {v}"))), + }; + let st = s.doc()?; + let d = &st.doc; + check_size(ids.iter().filter_map(|id| d.node(*id)?.path_data()), cmd)?; + let editable = d.editable(); + let mut out = vec![]; + for (i, id) in ids.iter().enumerate() { + let Some(lc) = d.node(*id).filter(|_| editable(*id)).and_then(LiveCorners::of) else { continue }; + let corners = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) { + Some(given) => { + let n = lc.base.anchor_count(); + if let Some(past) = given.iter().find(|k| **k >= n) { + return Err(bad(cmd, format!("object {id} has {n} anchors, so no anchor {past}"))); + } + given.iter().copied().filter(|k| lc.corner(*k).is_some()).collect() + } + None => st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)), + }; + if !corners.is_empty() { + out.push((*id, corners)); + } + } + if out.is_empty() { + return Err(bad(cmd, "choose anchors where two sides meet at an angle: only those take a corner")); + } + Ok(out) +} + +/// Cut `radius` and `kind` on `corners` as one step (none when they have them already). +fn edit_corners(s: &mut Session, label: &str, corners: Vec<(NodeId, BTreeSet)>, radius: f64, kind: Option) -> Result { + let d = &s.doc()?.doc; + let same = corners.iter().all(|(id, picked)| { + d.node(*id) + .and_then(LiveCorners::of) + .is_some_and(|c| picked.iter().all(|k| (c.drawn_radius(*k) - radius).abs() < 1e-9 && kind.is_none_or(|kd| c.kind(*k) == kd))) + }); + let out = json!({ + "ids": corners.iter().map(|(id, _)| id.0).collect::>(), + "corners": corners.iter().map(|(_, c)| c.len()).sum::(), + }); + if !same { + s.edit(label, |d, sel| { + for (id, picked) in corners { + let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { continue }; + // A cut changes the anchors, which is all a segment selection goes by. + sel.segments.remove(&id); + recut(path, live, sel.anchors.get_mut(&id), &picked, Some(radius), kind); + } + Ok(()) + })?; + } + Ok(out) +} + +fn corner_set(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.cornerSet"; + let radius = number_or(p, "radius", f64::NAN, C)?; + if !(0.0..=MAX_RADIUS).contains(&radius) { + return Err(bad(C, "`radius` must be from 0 to 1000000 pt")); + } + let kind = p + .get("kind") + .filter(|v| !v.is_null()) + .map(|v| { + serde_json::from_value::(v.clone()) + .map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}"))) + }) + .transpose()?; + let corners = named_corners(s, p, C)?; + edit_corners(s, "Set Corners", corners, radius, kind) +} + +fn corner_remove(s: &mut Session, p: &Value) -> Result { + let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?; + edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round)) +} diff --git a/crates/engine/src/cmd/addons/pathtools/effect_tests.rs b/crates/engine/src/cmd/addons/pathtools/effect_tests.rs new file mode 100644 index 0000000000..3465b72791 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/effect_tests.rs @@ -0,0 +1,186 @@ +//! Path Effects (`addon.path.*`) through the session: live on the canvas, the document's path left +//! alone, and Expand Appearance and a save keeping what they draw. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Effect, Node, NodeId}; +use vectorcraft_geom::{BezPath, Rect}; +use vectorcraft_render::Renderer; +use vectorcraft_render::effects::{GeomContext, apply_geometry_bez, effect_catalog, new_effect, preview, scale_effect}; + +use crate::Session; + +/// A black 4 pt stroke along `anchors`, unfilled. +fn stroked(anchors: Value, closed: bool) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.set([id])).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + (s, id) +} + +fn wave() -> (Session, NodeId) { + let anchors = json!([ + {"x": 20, "y": 100}, + {"x": 60, "y": 60, "in": [40, 60], "out": [80, 60]}, + {"x": 100, "y": 100}, + {"x": 140, "y": 140}, + {"x": 180, "y": 100} + ]); + stroked(anchors, false) +} + +/// Every Path Effect, with parameters that change the wave. +fn effects() -> Vec<(&'static str, Value)> { + vec![ + ("addon.path.dashes", json!({"dash1": 14, "gap1": 6, "dash2": 3, "gap2": 6})), + ("addon.path.dashes", json!({"dash1": 14, "gap1": 6, "alignCorners": true})), + ("addon.path.addAnchors", json!({"count": 3})), + ("addon.path.addAnchors", json!({"spacing": "distance", "distance": 15, "target": "curved"})), + ("addon.path.extend", json!({"startLength": 10, "endPercent": 10, "endShape": "arc"})), + ("addon.path.extend", json!({"startLength": -10, "endLength": -20})), + ("addon.path.close", json!({})), + ("addon.path.close", json!({"mode": "smooth"})), + ("addon.path.smooth", json!({"ratio": 0.3})), + ("addon.path.retract", json!({})), + ("addon.path.reverse", json!({})), + ("addon.path.simplify", json!({"tolerance": 200, "protectCorners": false})), + ("addon.path.split", json!({"anchors": "both"})), + ] +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn picture_of(d: &Document) -> Vec { + let r = Renderer::new().render_region(d, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true); + (0..200).flat_map(|y| (0..200).map(move |x| (x, y))).flat_map(|(x, y)| r.pixel(x, y)).collect() +} + +fn picture(s: &Session) -> Vec { + picture_of(&s.doc().unwrap().doc) +} + +/// The outline of `n`: its path, or those of the compound path it became. +fn outline(n: &Node) -> BezPath { + let mut out = n.path_data().map(|p| p.to_bezpath()).unwrap_or_default(); + n.children().into_iter().flatten().for_each(|c| out.extend(outline(c))); + out +} + +/// How many bytes of two pictures differ by more than antialiasing noise. +fn differing(a: &[u8], b: &[u8]) -> usize { + a.iter().zip(b).filter(|(x, y)| x.abs_diff(**y) > 8).count() +} + +#[test] +fn a_path_effect_draws_live_and_leaves_the_document_path() { + let (mut s, id) = stroked(json!([{"x": 10, "y": 50}, {"x": 190, "y": 50}]), false); + let solid = picture(&s); + let path = node(&s, id).path_data().cloned(); + s.execute("effect.apply", &json!({"effect": "addon.path.dashes", "params": {"dash1": 20, "gap1": 20}})).unwrap(); + assert_eq!(node(&s, id).path_data().cloned(), path, "only the effect holds the geometry"); + let dashed = picture(&s); + let at = |pic: &[u8], x: usize| pic[(50 * 200 + x) * 4]; + assert!(at(&solid, 45) < 40 && at(&dashed, 45) > 200, "a gap: {}", at(&dashed, 45)); + assert!(at(&dashed, 15) < 40, "a dash"); + // Hiding it draws the path again. + s.execute("effect.setParams", &json!({"index": 0, "visible": false})).unwrap(); + assert_eq!(picture(&s), solid); +} + +#[test] +fn a_path_effect_moves_the_bounds_the_object_is_measured_by() { + let (mut s, id) = stroked(json!([{"x": 50, "y": 50}, {"x": 150, "y": 50}]), false); + s.execute("effect.apply", &json!({"effect": "addon.path.extend", "params": {"startLength": 0, "endLength": 30}})).unwrap(); + let drawn = preview::bounds_of(&s.doc().unwrap().doc, &[id], true).unwrap(); + assert!((drawn.x1 - 180.0).abs() < 3.0, "{drawn:?}"); + let pic = picture(&s); + assert!(pic[(50 * 200 + 170) * 4] < 40, "and draws there"); +} + +#[test] +fn expand_appearance_writes_the_outline_the_effect_draws() { + for (effect, params) in effects() { + let (mut s, id) = wave(); + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + let n = node(&s, id); + let before = n.path_data().cloned().unwrap(); + let live = apply_geometry_bez(&n.appearance.effects, &before.to_bezpath(), before.bounds().unwrap(), &GeomContext::of(&n)); + let pic = picture(&s); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let expanded = node(&s, id); + assert!(expanded.appearance.effects.is_empty(), "{effect} {params}"); + let (out, want) = (outline(&expanded), live); + assert_eq!(out.elements().len(), want.elements().len(), "{effect} {params}"); + for (a, b) in out.elements().iter().zip(want.elements()) { + assert!(a.is_finite() && format!("{a:.4?}") == format!("{b:.4?}"), "{effect} {params}: {a:?} {b:?}"); + } + assert_eq!(differing(&pic, &picture(&s)), 0, "{effect} {params}"); + } +} + +#[test] +fn path_effects_round_trip_through_a_save_and_scale_their_distances() { + for (effect, params) in effects() { + let (mut s, id) = wave(); + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(restored.node(id).unwrap().appearance.effects, node(&s, id).appearance.effects, "{effect} {params}"); + assert_eq!(picture_of(&restored), picture(&s), "{effect} {params}"); + } + let mut e = new_effect("addon.path.dashes", &json!({"dash1": 10})).unwrap(); + scale_effect(&mut e, 2.0); + assert_eq!((e.params["dash1"].as_f64(), e.params["gap1"].as_f64()), (Some(20.0), Some(12.0))); +} + +#[test] +fn undo_takes_a_path_effect_off_in_one_step() { + let (mut s, id) = wave(); + s.execute("effect.apply", &json!({"effect": "addon.path.reverse"})).unwrap(); + assert_eq!(node(&s, id).appearance.effects.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, id).appearance.effects.is_empty()); +} + +/// A file's effects skip the checks `effect.apply` makes: whatever they hold, the object draws and +/// expands. +#[test] +fn path_effects_with_junk_params_from_a_file_draw_and_expand() { + let junk = [ + json!(null), + json!("x"), + json!({"dash1": 1e308, "gap1": -1e308, "offset": "x", "alignCorners": 3}), + json!({"count": 1e308, "maxCount": 1e308, "distance": -1e308, "spacing": "distance", "target": []}), + json!({"startLength": 1e308, "endPercent": -1e308, "endShape": {}, "mode": 1, "ratio": "x", "handles": "shorter", "length": 1e308}), + json!({"tolerance": 1e308, "protectCorners": "no", "anchors": null, "startPercent": 1e308, "startShape": "arc"}), + ]; + let ids = effect_catalog().into_iter().map(|e| e.id).filter(|id| id.starts_with("addon.path.")); + let stack: Vec = + ids.flat_map(|id| junk.iter().map(move |params| Effect { id: id.into(), params: params.clone(), visible: true })).collect(); + let (mut s, id) = wave(); + s.edit("Junk", |d, _| { + if let Some(n) = d.node_mut(id) { + n.appearance.effects = stack; + } + Ok(()) + }) + .unwrap(); + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + picture_of(&vectorcraft_format::load(&saved).unwrap()); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert!(node(&s, id).appearance.effects.is_empty()); +} + +#[test] +fn exports_write_the_dashes_as_paths() { + let (mut s, _) = wave(); + s.execute("effect.apply", &json!({"effect": "addon.path.dashes", "params": {"dash1": 10, "gap1": 10}})).unwrap(); + let v = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + let moves = svg.iter().filter(|c| **c == b'M').count(); + assert!(moves > 5, "the exported art holds the dashes: {moves}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs new file mode 100644 index 0000000000..4c1ba7e2dd --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -0,0 +1,137 @@ +//! The Parametric Shape Tool's commands (`addon.pathtools.shape.*`): draw a parametric shape, change +//! one's numbers, and turn plain rectangles, ellipses and regular polygons into them. A parametric +//! shape is an ordinary path whose numbers sit in one entry of its object data +//! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{FillRule, PathData, Point}; +use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise}; +use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json}; + +use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection}; +use crate::{EngineError, Result, Session}; + +/// The undo step's name and the command's label. +const CONVERT: &str = "Convert to Parametric Shape"; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.shape.create", + "Parametric Shape", + [], + None, + "{center: [x, y], kind?: \"rectangle\"|\"ellipse\"|\"polygon\" (default)|\"star\"|\"ring\"|\"arrow\"|\"cross\"|\"heart\"|\"gear\"|\"bubble\" (a speech bubble), width?, height?: 0.01..16384 pt (100), rotation?: degrees clockwise (0: upright), count?: 3..1000 (a polygon's sides, a star's points, a gear's teeth), a?, b?: the kind's own values (star: inner radius 0.01..1 of the outer, 0.5; ring: hole 0.01..0.99 of the size, 0.5; arrow: head length and shaft width 0.05..0.95, 0.4 and 0.4; cross: bar offset −0.9..0.9 (0, − up) and arm thickness 0.05..0.95 (1/3); heart: notch depth and point roundness 0..1 (0.4 and 0); gear: tooth height 0.01..0.9 (0.2); bubble: tail height 0.05..0.9 (0.25) and tail tip −1..1 across (−0.4)), radius?: corner radius 0..16384 pt (0; no corner rounds past the middle of a side)} draw a parametric shape with the current paint, selected, as one undo step; it stays editable with addon.pathtools.shape.set until its anchors are edited (moving, turning or scaling it keeps it) → {id, shape}", + has_doc, + create + ), + cmd!( + "addon.pathtools.shape.set", + "Edit Parametric Shape", + [], + None, + "{id, kind?, center?, width?, height?, rotation?, count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}", + has_doc, + set + ), + cmd!( + "addon.pathtools.shape.convert", + "Convert to Parametric Shape", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ids?: [id…] (default: the selection)} make each plain closed path that is a rectangle, an ellipse or a polygon with equal sides and corners (stretched along its own axes at most) a parametric shape of the same outline, as one undo step → {ids (converted)}", + has_selection, + convert + ), + ] +} + +/// Give path node `n` the outline `path` of shape `s` and keep its numbers; a live shape goes. +fn shape_node(n: &mut Node, s: &ParametricShape, path: PathData) { + let entry = stored(s, &path); + if let NodeKind::Path { path: p, live, .. } = &mut n.kind { + *p = path; + *live = None; + } + n.edit_attrs(|a| match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = entry, + None => a.data.push((KEY.into(), entry)), + }); +} + +/// The outline of `s`, checked already. +fn outline(s: &ParametricShape, cmd: &str) -> Result { + s.path().ok_or_else(|| bad(cmd, "the shape's numbers are out of range")) +} + +fn create(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.shape.create"; + if p.get("center").is_none_or(Value::is_null) { + return Err(bad(C, "`center` must be [x, y]")); + } + let shape = apply(ParametricShape::new(ShapeKind::Polygon, Point::ZERO, 100.0, 100.0), p).map_err(|e| bad(C, e))?; + let path = outline(&shape, C)?; + let parent = s.doc()?.target_parent()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + // shortcut: always on top of the insertion layer, as Draw Normal; honour Draw Behind/Inside if asked. + let id = s.edit(CREATE, |d, sel| { + let id = d.alloc_id(); + let mut n = Node::new(id, NodeKind::Path { path: PathData::default(), rule: FillRule::NonZero, live: None, clipping: false, guide: false }); + shape_node(&mut n, &shape, path); + look.apply(d, &mut n); + d.insert(parent, usize::MAX, n)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0, "shape": to_json(&shape) })) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.shape.set"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(C, "the path is locked or hidden")); + } + let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?; + let shape = apply(old, p).map_err(|e| bad(C, e))?; + if shape != old { + let path = outline(&shape, C)?; + s.edit(EDIT, |d, sel| { + shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + sel.anchors.remove(&id); + sel.segments.remove(&id); + Ok(()) + })?; + } + Ok(json!({ "id": id.0, "shape": to_json(&shape) })) +} + +fn convert(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.shape.convert"; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let mut found = vec![]; + for id in roots { + let Some(n) = d.node(id).filter(|n| d.is_editable(id) && read(n).is_none()) else { continue }; + if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind + && let Some(shape) = recognise(path) + { + found.push((id, shape, outline(&shape, C)?)); + } + } + if found.is_empty() { + return Err(bad(C, "select plain rectangles, ellipses or regular polygons to convert")); + } + let ids: Vec = found.iter().map(|(id, ..)| id.0).collect(); + s.edit(CONVERT, |d, sel| { + for (id, shape, path) in found { + shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + sel.anchors.remove(&id); + sel.segments.remove(&id); + } + Ok(()) + })?; + Ok(json!({ "ids": ids })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/shared_edge.rs b/crates/engine/src/cmd/addons/pathtools/shared_edge.rs new file mode 100644 index 0000000000..e5d61c47b0 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/shared_edge.rs @@ -0,0 +1,164 @@ +//! The Shared Edge Merge Tool's command and Keep Shared Points Together: with that option on, the +//! add-on's own commands that move an anchor (Slide Anchor Along Path, Extend Path, Set Anchor) take +//! the anchors coincident with it along. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{AnchorRef, Document, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point, Vec2}; +use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_tools::addons::shared_edge::{DIAMETER, DIAMETER_RANGE, ID}; + +use super::super::super::{CommandSpec, always, bad, checked_id, cmd, finite_numbers, has_doc, number_or, switch_or, text_param}; +use super::{edit_whole, set_path}; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.mergeEdge", + "Merge Shared Edge", + [], + None, + "{a, b: two path ids (they needn't be selected), at: [x, y] (where), diameter?: pt 0.25..200 (20; how near `at` the edge is looked for), tolerance?: pt 0..3 (0.002; how near two anchors count as coincident), follow?: \"average\" (half way between the two)|\"a\"|\"b\" (keep that path's outline), ends?: bool (false: true makes an end even where the paths could merge)} where the paths touch at two coincident anchors, one each side of `at`, replace the stretches between them with one shared edge; stretches much longer one than the other (by over 10%) or leaving an end at over 120° aren't merged. Otherwise make an end there: two near anchors meet, and an anchor only one path has there is matched by a new one on the other. Each path stays closed or open; one undo step → {a, b, made: \"edge\"|\"end\"|\"nothing\" (merged already)}", + has_doc, + merge_edge + ), + cmd!( + "addon.pathtools.movePointsTogether", + "Keep Shared Points Together", + [], + None, + "{enabled?: bool (default: the opposite of now)} Keep Shared Points Together: whether anchors coincident (within the Shared Edge Merge Tool's `tolerance`) with one that Slide Anchor Along Path, Extend Path or Set Anchor moves move with it, on any editable path (the `together` option of tool `sharedEdge`, kept with the preferences; off by default) → {enabled}", + always, + move_points_together + ), + ] +} + +/// A path a merge may edit. +fn merge_path<'a>(d: &'a Document, id: NodeId, cmd: &str) -> Result<&'a PathData> { + if !d.is_editable(id) { + return Err(bad(cmd, "the path is locked or hidden")); + } + match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, guide: false, .. }) => Ok(path), + _ => Err(bad(cmd, "`a` and `b` must be two different paths")), + } +} + +fn merge_edge(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.mergeEdge"; + let a = checked_id(s, p.get("a").unwrap_or(&Value::Null), C)?; + let b = checked_id(s, p.get("b").unwrap_or(&Value::Null), C)?; + if a == b { + return Err(bad(C, "`a` and `b` must be two different paths")); + } + let [x, y] = p.get("at").and_then(finite_numbers::<2>).ok_or_else(|| bad(C, "`at` must be [x, y]"))?; + let at = Point::new(x, y); + let diameter = number_or(p, "diameter", DIAMETER, C)?; + if !(DIAMETER_RANGE.0..=DIAMETER_RANGE.1).contains(&diameter) { + return Err(bad(C, "`diameter` must be from 0.25 to 200 pt")); + } + let tolerance = number_or(p, "tolerance", pt::COINCIDENCE, C)?; + if !(0.0..=pt::MAX_COINCIDENCE).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 0 to 3 pt")); + } + let follow = match text_param(p, "follow", C)? { + None => pt::Follow::Average, + Some(f) => pt::Follow::parse(f).ok_or_else(|| bad(C, "`follow` must be \"average\", \"a\" or \"b\""))?, + }; + let ends = switch_or(p, "ends", false, C)?; + let d = &s.doc()?.doc; + let (pa, pb) = (merge_path(d, a, C)?, merge_path(d, b, C)?); + let radius = diameter / 2.0; + let edge = if ends { None } else { pt::stretches_at(pa, pb, at, radius, tolerance) }; + let plan = edge.or_else(|| pt::ends_at(pa, pb, at, radius)).ok_or_else(|| bad(C, "the paths have nothing to merge there"))?; + let (na, nb) = pt::apply_merge(pa, pb, &plan, follow).ok_or_else(|| bad(C, "the paths have nothing to merge there"))?; + let changed: Vec<(NodeId, PathData)> = + [(a, pa, na), (b, pb, nb)].into_iter().filter(|(_, old, new)| *old != new).map(|(id, _, new)| (id, new)).collect(); + let made = match plan { + _ if changed.is_empty() => "nothing", + pt::MergePlan::Edge { .. } => "edge", + pt::MergePlan::Ends { .. } => "end", + }; + edit_whole(s, "Merge Shared Edge", changed)?; + Ok(json!({ "a": a.0, "b": b.0, "made": made })) +} + +fn move_points_together(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.movePointsTogether"; + let now = s.tool_options_of(ID)["together"].as_bool().unwrap_or(false); + let enabled = switch_or(p, "enabled", !now, C)?; + s.set_tool_options(Some(ID), &Map::from_iter([("together".to_string(), json!(enabled))])); + Ok(json!({ "enabled": enabled })) +} + +/// Anchors to move along with others: each with how far. +pub(super) type SharedPoints = Vec<(NodeId, AnchorRef, Vec2)>; + +/// With Keep Shared Points Together on, the anchors of editable paths coincident with an anchor +/// that `changed` (paths in their new form) moves, and not moving themselves. Subpaths whose +/// anchors `changed` adds or removes move none: their anchors stay put. +pub(super) fn shared_points<'a>(s: &Session, changed: impl IntoIterator) -> Result { + let options = s.tool_options_of(ID); + if options["together"].as_bool() != Some(true) { + return Ok(vec![]); + } + let tol = options["tolerance"].as_f64().unwrap_or(pt::COINCIDENCE); + let d = &s.doc()?.doc; + let mut moved: BTreeSet<(NodeId, AnchorRef)> = BTreeSet::new(); + let mut from: Vec<(Point, Vec2)> = vec![]; + for (id, new) in changed { + let Some(old) = d.node(id).and_then(|n| n.path_data()) else { continue }; + for (si, (o, n)) in old.subpaths.iter().zip(&new.subpaths).enumerate().filter(|(_, (o, n))| o.anchors.len() == n.anchors.len()) { + for (ai, (x, y)) in o.anchors.iter().zip(&n.anchors).enumerate().filter(|(_, (x, y))| x.p != y.p) { + moved.insert((id, (si, ai))); + from.push((x.p, y.p - x.p)); + } + } + } + let mut out = vec![]; + if from.is_empty() { + return Ok(out); + } + from.sort_by(|a, b| a.0.x.total_cmp(&b.0.x)); + let editable = d.editable(); + d.walk(|n| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return }; + if !editable(n.id) { + return; + } + for (si, ai, a) in path.anchors() { + let start = from.partition_point(|(p, _)| p.x < a.p.x - tol); + let mut near = from.iter().skip(start).take_while(|(p, _)| p.x <= a.p.x + tol); + if let Some((_, by)) = near.find(|(p, _)| p.distance(a.p) <= tol) + && !moved.contains(&(n.id, (si, ai))) + { + out.push((n.id, (si, ai), *by)); + } + } + }); + Ok(out) +} + +/// Move the anchors [`shared_points`] found; what they are on stops being a live shape. +pub(super) fn move_shared(d: &mut Document, shared: SharedPoints) { + let mut by_path: BTreeMap> = BTreeMap::new(); + for (id, at, by) in shared { + by_path.entry(id).or_default().push((at, by)); + } + for (id, anchors) in by_path { + let Some(mut np) = d.node(id).and_then(|n| n.path_data()).cloned() else { continue }; + for ((si, ai), by) in anchors { + if let Some(a) = np.anchor_mut(si, ai) { + a.translate(by); + } + } + set_path(d, id, np); + } +} diff --git a/crates/engine/src/cmd/addons/pathtools/shared_edge/tests.rs b/crates/engine/src/cmd/addons/pathtools/shared_edge/tests.rs new file mode 100644 index 0000000000..3ffe2fea7c --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/shared_edge/tests.rs @@ -0,0 +1,204 @@ +//! The Shared Edge Merge Tool's command and Keep Shared Points Together: one undo step each, bad +//! params refused, the tool's click through the session, and only the add-on's commands affected. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{PathData, Point}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +use crate::{Session, ViewInfo}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn line(s: &mut Session, pts: &[(f64, f64)], closed: bool) -> NodeId { + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap()) +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn points(s: &Session, id: NodeId) -> Vec { + path(s, id).anchors().map(|(_, _, a)| a.p).collect() +} + +/// Two closed shapes with a bent edge each between (100, 100) and (200, 100). +fn shapes(s: &mut Session) -> (NodeId, NodeId) { + let a = line(s, &[(100.0, 100.0), (150.0, 104.0), (200.0, 100.0), (200.0, 50.0), (100.0, 50.0)], true); + let b = line(s, &[(200.0, 100.0), (150.0, 96.0), (100.0, 100.0), (100.0, 150.0), (200.0, 150.0)], true); + (a, b) +} + +#[test] +fn merge_edge_replaces_both_stretches_as_one_undo_step() { + let mut s = session(); + let (a, b) = shapes(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let (pa, pb) = (path(&s, a), path(&s, b)); + let n = steps(&s); + let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100]})).unwrap(); + assert_eq!(r, json!({"a": a.0, "b": b.0, "made": "edge"})); + assert_eq!(steps(&s), n + 1); + assert!(path(&s, a).subpaths[0].closed && path(&s, b).subpaths[0].closed); + assert_eq!(points(&s, a)[..3], [Point::new(100.0, 100.0), Point::new(150.0, 100.0), Point::new(200.0, 100.0)]); + assert_eq!(points(&s, b)[..3], [Point::new(200.0, 100.0), Point::new(150.0, 100.0), Point::new(100.0, 100.0)]); + // Nothing left to do: no step. + let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100]})).unwrap(); + assert_eq!(r["made"], json!("nothing")); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s, a), path(&s, b)), (pa, pb)); +} + +#[test] +fn merge_edge_follows_the_path_asked_and_makes_ends() { + let mut s = session(); + let (a, b) = shapes(&mut s); + let pa = path(&s, a); + s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100], "follow": "a"})).unwrap(); + assert_eq!(path(&s, a), pa); + assert_eq!(points(&s, b)[1], Point::new(150.0, 104.0)); + // Ends asked for: the near anchors of two lines meet, one undo step. + let c = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)], false); + let d = line(&mut s, &[(54.0, 200.0), (90.0, 240.0)], false); + let n = steps(&s); + let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": c.0, "b": d.0, "at": [52, 200], "ends": true})).unwrap(); + assert_eq!((r["made"].clone(), steps(&s)), (json!("end"), n + 1)); + assert_eq!((points(&s, c)[1], points(&s, d)[0]), (Point::new(52.0, 200.0), Point::new(52.0, 200.0))); +} + +#[test] +fn merge_edge_refuses_bad_params_and_locked_paths() { + let mut s = session(); + let (a, b) = shapes(&mut s); + let (i, j) = (a.0, b.0); + let n = steps(&s); + for p in [ + json!({}), + json!({"a": i, "b": i, "at": [125, 100]}), + json!({"a": i, "b": j}), + json!({"a": i, "b": j, "at": [1]}), + json!({"a": i, "b": j, "at": [1, "x"]}), + json!({"a": i, "b": j, "at": [125, 100], "diameter": 0.1}), + json!({"a": i, "b": j, "at": [125, 100], "diameter": 201}), + json!({"a": i, "b": j, "at": [125, 100], "tolerance": 3.5}), + json!({"a": i, "b": j, "at": [125, 100], "tolerance": -1}), + json!({"a": i, "b": j, "at": [125, 100], "follow": "up"}), + json!({"a": i, "b": j, "at": [125, 100], "ends": 1}), + json!({"a": i, "b": u64::MAX, "at": [125, 100]}), + json!({"a": i, "b": j, "at": [390, 290]}), + ] { + assert!(s.execute("addon.pathtools.mergeEdge", &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + s.execute("select.set", &json!({"ids": [i]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + assert!(s.execute("addon.pathtools.mergeEdge", &json!({"a": i, "b": j, "at": [125, 100]})).is_err()); +} + +#[test] +fn the_tool_merges_unselected_paths_on_a_click_with_shift_following_the_upper() { + let mut s = session(); + let (lower, upper) = shapes(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("sharedEdge", view).unwrap(); + let keep = path(&s, upper); + let n = steps(&s); + let shifted = |kind| { + let mut e = PointerEvent::new(kind, 125.0, 100.0); + e.mods = Mods { shift: true, ..Mods::default() }; + e + }; + s.pointer(&shifted(PointerKind::Down), view).unwrap(); + s.pointer(&shifted(PointerKind::Up), view).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(path(&s, upper), keep); + assert_eq!(points(&s, lower)[1], Point::new(150.0, 96.0)); +} + +#[test] +fn keep_shared_points_together_is_off_by_default_and_a_preference_of_the_tool() { + let mut s = session(); + assert_eq!(s.tool_options_of("sharedEdge")["together"], json!(false)); + assert_eq!(s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap(), json!({"enabled": true})); + assert_eq!(s.tool_options_of("sharedEdge")["together"], json!(true), "kept with another tool active"); + assert_eq!(s.execute("addon.pathtools.movePointsTogether", &json!({})).unwrap(), json!({"enabled": false})); + assert!(s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": 1})).is_err()); +} + +#[test] +fn a_slide_takes_coincident_anchors_along_in_one_step_when_the_option_is_on() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (200.0, 100.0), (300.0, 100.0)], false); + let b = line(&mut s, &[(200.0, 100.0), (200.0, 200.0)], false); + let far = line(&mut s, &[(200.0, 101.0), (250.0, 200.0)], false); + let slide = json!({"id": a.0, "anchor": 1, "t": 0.5}); + let n = steps(&s); + s.execute("addon.pathtools.slideAnchor", &slide).unwrap(); + assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0), "off: it stays"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap(); + s.execute("addon.pathtools.slideAnchor", &slide).unwrap(); + assert_eq!(steps(&s), n + 1); + let moved = points(&s, a)[1]; + assert!(moved.distance(Point::new(250.0, 100.0)) < 1e-6, "{moved:?}"); + assert!(points(&s, b)[0].distance(moved) < 1e-9); + assert_eq!(points(&s, b)[1], Point::new(200.0, 200.0)); + assert_eq!(points(&s, far)[0], Point::new(200.0, 101.0), "not coincident"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0)); + // A wider coincidence reaches it, and a locked path stays. + s.set_tool_options(Some("sharedEdge"), &serde_json::Map::from_iter([("tolerance".to_string(), json!(2))])); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("addon.pathtools.slideAnchor", &slide).unwrap(); + assert!(points(&s, far)[0].distance(Point::new(250.0, 101.0)) < 1e-6); + assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0)); +} + +#[test] +fn set_anchor_and_extend_take_coincident_anchors_along_but_built_in_moves_do_not() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (200.0, 100.0)], false); + let b = line(&mut s, &[(200.0, 100.0), (200.0, 200.0)], false); + s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap(); + // Set Anchor on one selected anchor. + s.select(|_, sel| { + sel.set([a]); + sel.anchors.insert(a, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let n = steps(&s); + s.execute("addon.pathtools.setAnchor", &json!({"x": 220, "y": 90})).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(points(&s, b), [Point::new(220.0, 90.0), Point::new(200.0, 200.0)]); + // An edit that moves no anchor moves none. + s.execute("addon.pathtools.corner", &json!({})).unwrap(); + assert_eq!(points(&s, b)[0], Point::new(220.0, 90.0)); + // Extend Path moves an end only when it adds no anchor. + s.execute("addon.pathtools.extend", &json!({"id": a.0, "end": "end", "length": 10, "mode": "bezier"})).unwrap(); + let end = points(&s, a)[1]; + assert!(points(&s, b)[0].distance(end) < 1e-9); + let end = points(&s, b)[0]; + s.execute("addon.pathtools.extend", &json!({"id": a.0, "end": "end", "length": 10})).unwrap(); + assert_eq!(points(&s, a).len(), 3); + assert_eq!(points(&s, b)[0], end, "the end it left stays with what shares it"); + // The app's own moves are untouched by the option. + s.select(|_, sel| { + sel.set([a]); + sel.anchors.insert(a, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 5})).unwrap(); + assert_eq!(points(&s, b)[0], end); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs new file mode 100644 index 0000000000..32bcc0c3b3 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -0,0 +1,873 @@ +//! Path Precision Tools' commands: each one undo step, bad params refused, and the tools' gestures +//! through the session. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveCorners, LiveShape, NodeId}; +use vectorcraft_geom::shapes::CornerKind; +use vectorcraft_geom::{AnchorKind, PathData, Point}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::{Session, ViewInfo}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn line(s: &mut Session, pts: &[(f64, f64)], closed: bool) -> NodeId { + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()) +} + +/// A circle of 16 anchors about (100, 100), radius 50, selected. +fn circle(s: &mut Session) -> NodeId { + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + e +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +/// Direct-select anchors `anchors` (of subpath 0) of `id`. +fn select_anchors(s: &mut Session, id: NodeId, anchors: &[usize]) { + s.select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, anchors.iter().map(|a| (0, *a)).collect::>()); + }) + .unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +#[test] +fn the_brush_removes_anchors_under_it_keeping_the_shape() { + let mut s = session(); + let e = circle(&mut s); + assert_eq!(path(&s, e).anchor_count(), 16); + let bounds = path(&s, e).bounds().unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.erase", &json!({"points": [[150, 40], [150, 160]], "diameter": 60, "tolerance": 100})).unwrap(); + let left = path(&s, e).anchor_count(); + assert!(left < 16 && left > 8, "{left}"); + assert_eq!(r["removed"], json!(16 - left)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let b = path(&s, e).bounds().unwrap(); + assert!((b.x1 - bounds.x1).abs() < 2.5 && (b.y0 - bounds.y0).abs() < 0.01, "{b:?} vs {bounds:?}"); + // The anchors away from the brush stay: those on the left of the circle. + assert!(path(&s, e).anchors().filter(|(_, _, a)| a.p.x < 100.0).count() >= 7); + // A plain delete takes every anchor under it, whatever the shape. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.erase", &json!({"points": [[150, 40], [150, 160]], "diameter": 60, "plain": true})).unwrap(); + assert!(path(&s, e).anchors().all(|(_, _, a)| a.p.x < 121.0)); + // Nothing under the brush: no step. + let n = steps(&s); + s.execute("addon.pathtools.erase", &json!({"points": [[390, 290]], "diameter": 5})).unwrap(); + assert_eq!(steps(&s), n); + refuses( + &mut s, + "addon.pathtools.erase", + &[ + json!({}), + json!({"points": "x"}), + json!({"points": [[1, "y"]]}), + json!({"points": [[100, 100]], "diameter": 0}), + json!({"points": [[100, 100]], "diameter": 3000}), + json!({"points": [[100, 100]], "tolerance": 0}), + json!({"points": [[100, 100]], "plain": "yes"}), + ], + ); +} + +#[test] +fn the_brush_tool_is_one_undo_step_per_stroke() { + let mut s = session(); + let e = circle(&mut s); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("anchorEraserBrush", view).unwrap(); + assert_eq!(s.tool_id(), "anchorEraserBrush"); + s.set_tool_option("size", &json!(60)); + s.set_tool_option("tolerance", &json!(100)); + let n = steps(&s); + for (k, y) in + [(PointerKind::Down, 40.0), (PointerKind::Drag, 80.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 160.0), (PointerKind::Up, 160.0)] + { + s.pointer(&PointerEvent::new(k, 150.0, y), view).unwrap(); + } + assert_eq!(steps(&s), n + 1); + assert!(path(&s, e).anchor_count() < 16); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, e).anchor_count(), 16); +} + +#[test] +fn extend_lengthens_and_shortens_an_end() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 100.0), (100.0, 100.0)], false); + let n = steps(&s); + s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "end", "length": 50})).unwrap(); + assert_eq!(path(&s, l).subpaths[0].anchors.last().unwrap().p, Point::new(150.0, 100.0)); + assert_eq!(steps(&s), n + 1); + s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "start", "to": [-30, 120], "mode": "bezier"})).unwrap(); + assert!((path(&s, l).subpaths[0].anchors[0].p.x + 30.0).abs() < 1e-6); + let r = s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "end", "length": -60})).unwrap(); + assert_eq!(r["length"], json!(-60.0)); + assert!((path(&s, l).length() - 120.0).abs() < 1e-3, "{}", path(&s, l).length()); + assert_eq!(steps(&s), n + 3); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + refuses( + &mut s, + "addon.pathtools.extend", + &[ + json!({"id": l.0, "end": "end"}), + json!({"id": l.0, "end": "middle", "length": 5}), + json!({"id": l.0, "end": "end", "length": 5, "to": [1, 1]}), + json!({"id": l.0, "end": "end", "length": 5, "mode": "spiral"}), + json!({"id": l.0, "end": "end", "length": -1000}), + json!({"id": l.0, "end": "end", "length": 1e9}), + json!({"id": l.0, "end": "end", "to": [1]}), + json!({"id": l.0, "subpath": 3, "end": "end", "length": 5}), + json!({"id": sq.0, "end": "end", "length": 5}), + json!({"id": 99999, "end": "end", "length": 5}), + ], + ); +} + +#[test] +fn inspect_reads_the_path_under_a_point() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap()); + let v = s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 99, "y": 1})).unwrap(); + assert_eq!((v["closed"].clone(), v["anchors"].clone()), (json!(true), json!(4))); + assert!((v["length"].as_f64().unwrap() - 300.0).abs() < 1e-6 && (v["area"].as_f64().unwrap() - 5000.0).abs() < 1e-6); + assert!((v["anchor"]["angle"].as_f64().unwrap() - 90.0).abs() < 1e-9); + assert!(v["radius"].is_null()); + assert!(s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 1})).is_err()); + assert!(s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 1, "y": 1, "tolerance": -1})).is_err()); +} + +#[test] +fn smooth_corner_and_equalize_edit_the_selected_anchors_in_one_step_each() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + select(&mut s, &[r]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.smooth", &json!({})).unwrap()["anchors"], json!(4)); + assert!(path(&s, r).anchors().all(|(_, _, a)| a.kind == AnchorKind::Smooth && (a.h_out - a.p).hypot() > 39.0)); + assert_eq!(steps(&s), n + 1); + // Only the direct-selected anchor. + select_anchors(&mut s, r, &[0]); + s.execute("addon.pathtools.corner", &json!({})).unwrap(); + let p = path(&s, r); + assert!(!p.subpaths[0].anchors[0].has_out() && p.subpaths[0].anchors[1].has_out()); + assert_eq!(steps(&s), n + 2); + // Equalise: one handle made to match the other. + select_anchors(&mut s, r, &[1]); + s.execute("addon.pathtools.setAnchor", &json!({"outLength": 10})).unwrap(); + let a = path(&s, r).subpaths[0].anchors[1]; + assert!(((a.h_out - a.p).hypot() - 10.0).abs() < 1e-9 && (a.h_in - a.p).hypot() > 39.0); + s.execute("addon.pathtools.equalize", &json!({})).unwrap(); + let a = path(&s, r).subpaths[0].anchors[1]; + assert!(((a.h_out - a.p).hypot() - (a.h_in - a.p).hypot()).abs() < 1e-9); + // A selection with nothing to change makes no step. + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.equalize", &json!({})).unwrap()["anchors"], json!(0)); + assert_eq!(steps(&s), n); + refuses(&mut s, "addon.pathtools.smooth", &[json!({"ratio": 0.9}), json!({"ratio": "x"})]); + refuses(&mut s, "addon.pathtools.corner", &[json!({"retract": 1})]); +} + +#[test] +fn set_anchor_moves_anchors_and_sets_handles() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (50.0, 0.0), (100.0, 0.0)], false); + select_anchors(&mut s, l, &[1]); + let n = steps(&s); + s.execute("addon.pathtools.setAnchor", &json!({"x": 60, "y": 20, "outLength": 30, "outAngle": 90})).unwrap(); + let a = path(&s, l).subpaths[0].anchors[1]; + assert_eq!(a.p, Point::new(60.0, 20.0)); + assert!(a.h_out.distance(Point::new(60.0, -10.0)) < 1e-9, "{a:?}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.setAnchor", &[json!({}), json!({"x": "1"}), json!({"inLength": -2}), json!({"y": f64::MAX})]); +} + +#[test] +fn remove_keep_shape_takes_the_direct_selected_anchors() { + let mut s = session(); + let e = circle(&mut s); + // Selected whole: nothing to say which anchors go. + refuses(&mut s, "addon.pathtools.removeKeepShape", &[json!({})]); + select_anchors(&mut s, e, &[1, 5]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.removeKeepShape", &json!({})).unwrap()["removed"], json!(2)); + assert_eq!(path(&s, e).anchor_count(), 14); + assert_eq!(steps(&s), n + 1); +} + +#[test] +fn add_points_splits_selected_segments_evenly() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.addPoints", &json!({"count": 3})).unwrap()["added"], json!(3)); + let xs: Vec = path(&s, l).anchors().map(|(_, _, a)| a.p.x).collect(); + assert!(xs.iter().zip([0.0, 25.0, 50.0, 75.0, 100.0]).all(|(x, w)| (x - w).abs() < 1e-3), "{xs:?}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.addPoints", &[json!({"count": 0}), json!({"count": 101}), json!({"count": 1.5})]); + // An anchor alone selects no segment. + select_anchors(&mut s, l, &[1]); + refuses(&mut s, "addon.pathtools.addPoints", &[json!({})]); +} + +#[test] +fn close_joins_open_ends() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (50.0, 80.0)], false); + select(&mut s, &[l]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.close", &json!({"mode": "smooth"})).unwrap()["closed"], json!(1)); + assert!(path(&s, l).subpaths[0].closed); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.close", &[json!({}), json!({"mode": "round"})]); +} + +#[test] +fn crossings_add_anchors_or_cut_in_one_step() { + let mut s = session(); + let a = line(&mut s, &[(0.0, 0.0), (100.0, 100.0)], false); + let b = line(&mut s, &[(0.0, 100.0), (100.0, 0.0)], false); + select(&mut s, &[a, b]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.crossings", &json!({})).unwrap()["crossings"], json!(2)); + assert_eq!((path(&s, a).anchor_count(), path(&s, b).anchor_count()), (3, 3)); + assert!(path(&s, a).subpaths[0].anchors[1].p.distance(Point::new(50.0, 50.0)) < 1e-6); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("addon.pathtools.crossings", &json!({"cut": true})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 4, "{r}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.crossings", &[json!({"cut": "yes"}), json!({"ids": [123456]})]); +} + +// ---------- Parametric Shape Tool ---------- + +/// The parametric shape object `id` is now, as the tool reads it. +fn shape_of(s: &Session, id: NodeId) -> Option { + vectorcraft_tools::addons::parametric_shape::read(s.doc().unwrap().doc.node(id).unwrap()) +} + +fn star(s: &mut Session) -> NodeId { + let r = s.execute("addon.pathtools.shape.create", &json!({"kind": "star", "center": [200, 150], "width": 100, "height": 100})).unwrap(); + id_of(&r) +} + +#[test] +fn create_draws_a_selected_parametric_shape_in_one_step() { + let mut s = session(); + let n = steps(&s); + let r = s.execute("addon.pathtools.shape.create", &json!({"kind": "gear", "center": [200, 150], "count": 10, "a": 0.3, "radius": 2})).unwrap(); + let id = id_of(&r); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!((r["shape"]["kind"].clone(), r["shape"]["count"].clone(), r["shape"]["width"].clone()), (json!("gear"), json!(10), json!(100.0))); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + let g = shape_of(&s, id).unwrap(); + assert_eq!((g.count, g.a, g.radius), (10, 0.3, 2.0)); + assert!(path(&s, id).anchor_count() > 40, "40 tooth corners, rounded"); + // Every kind, with its defaults. + for kind in ["rectangle", "ellipse", "polygon", "star", "ring", "arrow", "cross", "heart", "gear", "bubble"] { + let id = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": kind, "center": [50, 50]})).unwrap()); + assert_eq!(shape_of(&s, id).map(|s| s.kind.id()), Some(kind)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 10); +} + +#[test] +fn set_changes_the_numbers_in_one_step_and_nothing_without_a_change() { + let mut s = session(); + let id = star(&mut s); + assert_eq!(path(&s, id).anchor_count(), 10); + let n = steps(&s); + let r = s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 8, "a": 0.3, "rotation": 15})).unwrap(); + assert_eq!((r["shape"]["count"].clone(), r["shape"]["rotation"].clone()), (json!(8), json!(15.0))); + assert_eq!(path(&s, id).anchor_count(), 16); + assert_eq!(steps(&s), n + 1); + // The same numbers again, or none: no step. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 8})).unwrap(); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0})).unwrap(); + assert_eq!(steps(&s), n + 1); + // Another kind takes its own defaults. + let r = s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "kind": "arrow"})).unwrap(); + assert_eq!((r["shape"]["a"].clone(), r["shape"]["rotation"].clone()), (json!(0.4), json!(15.0))); + assert_eq!(path(&s, id).anchor_count(), 7); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).anchor_count(), 16); +} + +#[test] +fn bad_shape_params_are_refused() { + let mut s = session(); + let id = star(&mut s); + let rect = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + let c = json!([10, 10]); + refuses( + &mut s, + "addon.pathtools.shape.create", + &[ + json!({}), + json!({"center": null}), + json!({"center": [1]}), + json!({"center": "here"}), + json!({"center": [1e300, 0]}), + json!({"center": c, "kind": "cloud"}), + json!({"center": c, "kind": 3}), + json!({"center": c, "count": 2}), + json!({"center": c, "count": 1001}), + json!({"center": c, "count": 4.5}), + json!({"center": c, "width": 0}), + json!({"center": c, "height": 16385}), + json!({"center": c, "width": "40"}), + json!({"center": c, "kind": "star", "a": 2}), + json!({"center": c, "kind": "bubble", "b": -1.5}), + json!({"center": c, "radius": -1}), + json!({"center": c, "rotation": "up"}), + ], + ); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[json!({}), json!({"id": rect.0, "count": 6}), json!({"id": 999_999}), json!({"id": id.0, "count": 0}), json!({"id": id.0, "width": -5})], + ); + s.execute("object.setProps", &json!({"ids": [id.0], "locked": true})).unwrap(); + refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "count": 6})]); +} + +#[test] +fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() { + let mut s = session(); + let id = star(&mut s); + // Moved, turned and scaled with the ordinary commands: still the shape, at its new place. + s.execute("object.move", &json!({"dx": 20, "dy": -10})).unwrap(); + assert!(shape_of(&s, id).is_some_and(|s| s.center.distance(Point::new(220.0, 140.0)) < 1e-6)); + s.execute("object.rotate", &json!({"angle": 30, "origin": [220, 140]})).unwrap(); + let r = shape_of(&s, id).unwrap(); + assert!((r.rotation + 30.0).abs() < 1e-6, "30° counter-clockwise is −30 here: {r:?}"); + s.execute("object.scale", &json!({"sx": 200, "origin": [220, 140]})).unwrap(); + let r = shape_of(&s, id).unwrap(); + assert!((r.width - 200.0).abs() < 1e-6 && r.center.distance(Point::new(220.0, 140.0)) < 1e-6, "{r:?}"); + let n = steps(&s); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap(); + assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1)); + assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays"); + // Stretched across its own axes (it is turned): skewed, so no longer. + s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap(); + assert_eq!(shape_of(&s, id), None); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(shape_of(&s, id).is_some(), "undo brings it back"); + // An anchor moved by hand: a plain path, which `set` refuses. + select_anchors(&mut s, id, &[2]); + s.execute("addon.pathtools.setAnchor", &json!({"x": 0})).unwrap(); + assert_eq!(shape_of(&s, id), None); + refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "count": 7})]); +} + +#[test] +fn convert_makes_plain_shapes_parametric_in_one_step() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 100, "height": 50})).unwrap()); + let p = id_of(&s.execute("shape.polygon", &json!({"cx": 200, "cy": 150, "radius": 40, "sides": 7})).unwrap()); + let st = id_of(&s.execute("shape.star", &json!({"cx": 300, "cy": 150, "radius1": 40, "radius2": 15})).unwrap()); + select(&mut s, &[r, p, st]); + let n = steps(&s); + let out = s.execute("addon.pathtools.shape.convert", &json!({})).unwrap(); + assert_eq!(out["ids"], json!([r.0, p.0])); + assert_eq!(steps(&s), n + 1); + assert_eq!(shape_of(&s, r).map(|s| s.kind.id()), Some("rectangle")); + assert_eq!(shape_of(&s, p).map(|s| (s.kind.id(), s.count)), Some(("polygon", 7))); + assert_eq!(shape_of(&s, st), None); + assert_eq!(path(&s, r).bounds().map(|b| b.center()), Some(Point::new(60.0, 45.0))); + // Nothing left to convert. + select(&mut s, &[r, st]); + refuses(&mut s, "addon.pathtools.shape.convert", &[json!({}), json!({"ids": [st.0]}), json!({"ids": [123456]})]); +} + +#[test] +fn the_shape_data_stays_out_of_svg_export() { + let mut s = session(); + let id = star(&mut s); + s.execute("object.setProps", &json!({"ids": [id.0], "data": {"pivot": "1,2"}})).unwrap(); + let key = vectorcraft_tools::addons::parametric_shape::KEY; + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(node.extras().attrs.as_deref().is_some_and(|a| a.data.iter().any(|(k, _)| k == key)), "kept with the object"); + assert!(shape_of(&s, id).is_some(), "setting other data keeps it a shape"); + let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default()); + assert!(svg.contains("data-pivot=\"1,2\""), "the object's own data still goes out: {svg}"); + assert!(!svg.contains(key) && !svg.contains("fp"") && !svg.contains("\"fp\""), "{svg}"); +} + +#[test] +fn the_tool_draws_one_step_per_drag_and_arrows_change_the_count() { + let mut s = session(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("parametricShape", view).unwrap(); + s.set_tool_option("kind", &json!("star")); + let n = steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 150.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), view).unwrap(); + s.tool_key(vectorcraft_tools::ToolKey::Up, vectorcraft_tools::Mods::default(), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 90.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 90.0), view).unwrap(); + assert_eq!(steps(&s), n + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let shape = shape_of(&s, id).unwrap(); + assert_eq!((shape.kind.id(), shape.count, shape.height, shape.rotation), ("star", 6, 120.0, 0.0)); + // Its size handle (lower right of its box) drags into one more step. + let corner = shape.frame() * Point::new(shape.width / 2.0, shape.height / 2.0); + for (k, x) in [(PointerKind::Down, corner.x), (PointerKind::Drag, corner.x + 30.0), (PointerKind::Up, corner.x + 30.0)] { + s.pointer(&PointerEvent::new(k, x, corner.y), view).unwrap(); + } + assert_eq!(steps(&s), n + 2); + assert!((shape_of(&s, id).unwrap().width - 180.0).abs() < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(shape_of(&s, id).map(|s| s.width), Some(120.0)); +} + +// ---------- Corner Tool ---------- + +/// A square (100, 100)–(300, 300), plain and selected: anchors from the top left, clockwise. +fn square(s: &mut Session) -> NodeId { + let id = line(s, &[(100.0, 100.0), (300.0, 100.0), (300.0, 300.0), (100.0, 300.0)], true); + select(s, &[id]); + id +} + +fn live(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).unwrap().live_shape().cloned() +} + +fn drawn(s: &Session, id: NodeId, corner: usize) -> f64 { + LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().drawn_radius(corner) +} + +#[test] +fn corner_set_cuts_live_corners_as_one_undo_step() { + let mut s = session(); + let id = square(&mut s); + let plain = path(&s, id); + let n = steps(&s); + // The selected path: all four. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 20, "kind": "chamfer"})).unwrap(); + assert_eq!(r, json!({"ids": [id.0], "corners": 4})); + assert_eq!((steps(&s), path(&s, id).anchor_count()), (n + 1, 8)); + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).map(|c| (c.drawn_radius(3), c.kind(3))).unwrap(); + assert_eq!(lc, (20.0, CornerKind::Chamfer)); + // The same again changes nothing: no step. + s.execute("addon.pathtools.cornerSet", &json!({"radius": 20, "kind": "chamfer"})).unwrap(); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s, id), live(&s, id)), (plain, None)); +} + +#[test] +fn corner_set_goes_by_anchors_the_selection_and_items_and_fits() { + let mut s = session(); + let id = square(&mut s); + let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false); + // Named anchors, of each path by `items`, at once; an open end takes none. + let items = json!([{"id": id.0, "anchors": [1]}, {"id": other.0, "anchors": [0, 1]}]); + let n = steps(&s); + let r = s.execute("addon.pathtools.cornerSet", &json!({"items": items, "radius": 5})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(2), n + 1)); + assert_eq!((drawn(&s, id, 1), drawn(&s, id, 0), drawn(&s, other, 1)), (5.0, 0.0, 5.0)); + // `ids` with `anchors`, keeping the kind each has. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "anchors": [1], "radius": 9})).unwrap(); + assert_eq!(drawn(&s, id, 1), 9.0); + // Direct-selected anchors: only their corners, which stay selected as they gain anchors. + select_anchors(&mut s, id, &[0]); + s.execute("addon.pathtools.cornerSet", &json!({"radius": 7})).unwrap(); + assert_eq!((drawn(&s, id, 0), drawn(&s, id, 2)), (7.0, 0.0)); + let sel = s.doc().unwrap().selection.anchors[&id].clone(); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert_eq!(c.corners_of(&sel), BTreeSet::from([0])); + // A radius that doesn't fit is drawn at what does. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "anchors": [2], "radius": 5000})).unwrap(); + assert!(drawn(&s, id, 2) <= 200.0 - 7.0 + 1e-9, "{}", drawn(&s, id, 2)); +} + +#[test] +fn corner_remove_makes_corners_sharp_and_a_path_plain_again() { + let mut s = session(); + let id = square(&mut s); + let plain = path(&s, id); + s.execute("addon.pathtools.cornerSet", &json!({"anchors": [0, 1], "radius": 10, "kind": "invertedRound"})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": id.0, "anchors": [0]}]})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s), drawn(&s, id, 0), drawn(&s, id, 1)), (json!(1), n + 1, 0.0, 10.0)); + s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap(); + assert_eq!((steps(&s), path(&s, id), live(&s, id)), (n + 2, plain, None)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(drawn(&s, id, 1), 10.0); +} + +#[test] +fn corner_commands_refuse_bad_params() { + let mut s = session(); + let id = square(&mut s); + let smooth = circle(&mut s); + let i = id.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i]}), + json!({"ids": [i], "radius": -1}), + json!({"ids": [i], "radius": 1e308}), + json!({"ids": [i], "radius": "big"}), + json!({"ids": [i], "radius": 5, "kind": "spiky"}), + json!({"ids": [i], "anchors": "all", "radius": 5}), + json!({"ids": [i], "anchors": [-1], "radius": 5}), + json!({"ids": [i], "anchors": [9], "radius": 5}), + json!({"ids": [u64::MAX], "radius": 5}), + json!({"items": 3, "radius": 5}), + json!({"items": [{"anchors": [0]}], "radius": 5}), + json!({"ids": [smooth.0], "radius": 5}), + ], + ); + refuses(&mut s, "addon.pathtools.cornerRemove", &[json!({"anchors": [9], "ids": [i]}), json!({"ids": [smooth.0]})]); + // Locked: left alone. + s.execute("object.lock", &json!({"ids": [i]})).ok(); + if !s.doc().unwrap().doc.is_editable(id) { + refuses(&mut s, "addon.pathtools.cornerSet", &[json!({"items": [{"id": i}], "radius": 5})]); + } +} + +#[test] +fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() { + let mut s = session(); + let id = square(&mut s); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("cornerTool", view).unwrap(); + s.set_tool_option("radius", &json!(15)); + let n = steps(&s); + let press = |s: &mut Session, k, x, y| s.pointer(&PointerEvent::new(k, x, y), view).unwrap(); + // A click on the top right anchor. + press(&mut s, PointerKind::Down, 300.0, 100.0); + press(&mut s, PointerKind::Up, 300.0, 100.0); + assert_eq!((steps(&s), drawn(&s, id, 1)), (n + 1, 15.0)); + // A drag from the bottom right anchor, previewed, one step. + press(&mut s, PointerKind::Down, 300.0, 300.0); + press(&mut s, PointerKind::Drag, 280.0, 280.0); + assert_eq!(drawn(&s, id, 2), 20.0, "the preview shows"); + press(&mut s, PointerKind::Drag, 270.0, 270.0); + press(&mut s, PointerKind::Up, 270.0, 270.0); + assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 2, 30.0)); + // A drag on the marker resizes; a double-click on it removes. + press(&mut s, PointerKind::Down, 270.0, 270.0); + press(&mut s, PointerKind::Drag, 260.0, 260.0); + press(&mut s, PointerKind::Up, 260.0, 260.0); + assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 3, 40.0)); + press(&mut s, PointerKind::DoubleClick, 260.0, 260.0); + assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 4, 0.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(drawn(&s, id, 2), 40.0); + // A click on a marker selects the corner and loads its values. + press(&mut s, PointerKind::Down, 285.0, 115.0); + press(&mut s, PointerKind::Up, 285.0, 115.0); + assert_eq!(steps(&s), n + 3, "selecting is no edit"); + assert_eq!(s.doc().unwrap().selection.anchors.get(&id).map(|a| a.len()), Some(2)); + // The bottom right one, resized by its marker, loads its radius. + press(&mut s, PointerKind::Down, 260.0, 260.0); + press(&mut s, PointerKind::Up, 260.0, 260.0); + assert_eq!(s.tool_options_of("cornerTool")["radius"], json!(40.0)); + // An Alt-marquee over the left side: both anchors, in one step. + let alt = vectorcraft_tools::Mods { alt: true, ..Default::default() }; + for (k, x, y) in [(PointerKind::Down, 50.0, 50.0), (PointerKind::Drag, 150.0, 350.0), (PointerKind::Up, 150.0, 350.0)] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(alt), view).unwrap(); + } + assert_eq!((steps(&s), drawn(&s, id, 0), drawn(&s, id, 3)), (n + 4, 40.0, 40.0)); +} + +// ---------- Slide Anchor Along Path ---------- + +#[test] +fn slide_anchor_moves_it_along_the_path_as_one_undo_step() { + let mut s = session(); + let e = circle(&mut s); + let before = path(&s, e); + let area = kurbo::Shape::area(&before.to_bezpath()).abs(); + let want = before.subpaths[0].segment(3); + let n = steps(&s); + let r = s.execute("addon.pathtools.slideAnchor", &json!({"id": e.0, "anchor": 3, "t": 0.5})).unwrap(); + assert!(r["strayed"].as_f64().unwrap() < 0.05, "{r}"); + let after = path(&s, e); + assert_eq!((steps(&s), after.anchor_count()), (n + 1, 16)); + assert!(after.subpaths[0].anchors[3].p.distance(kurbo::ParamCurve::eval(&want, 0.5)) < 1e-9); + assert!((kurbo::Shape::area(&after.to_bezpath()).abs() / area - 1.0).abs() < 1e-3); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, e), before); + // No move, no step. + s.execute("addon.pathtools.slideAnchor", &json!({"id": e.0, "anchor": 3, "t": 0})).unwrap(); + assert_eq!(steps(&s), n); +} + +#[test] +fn slide_anchor_refuses_bad_params() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false); + let i = l.0; + refuses( + &mut s, + "addon.pathtools.slideAnchor", + &[ + json!({"id": i, "anchor": 0, "t": 0.5}), + json!({"id": i, "anchor": 2, "t": -0.5}), + json!({"id": i, "anchor": 9, "t": 0.5}), + json!({"id": i, "anchor": 1, "t": 1.5}), + json!({"id": i, "anchor": 1}), + json!({"id": i, "t": 0.5}), + json!({"id": i, "subpath": 4, "anchor": 1, "t": 0.5}), + json!({"id": u64::MAX, "anchor": 1, "t": 0.5}), + ], + ); +} + +#[test] +fn the_slide_tool_previews_and_commits_one_step() { + let mut s = session(); + let l = line(&mut s, &[(100.0, 100.0), (200.0, 100.0), (300.0, 100.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("slideAnchor", view).unwrap(); + let n = steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 120.0), view).unwrap(); + let at = |s: &Session| path(s, l).subpaths[0].anchors[1].p; + assert!(at(&s).distance(Point::new(250.0, 100.0)) < 1e-3, "the preview shows"); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 90.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 90.0), view).unwrap(); + assert!(steps(&s) == n + 1 && at(&s).distance(Point::new(280.0, 100.0)) < 1e-3); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(at(&s), Point::new(200.0, 100.0)); +} + +fn ids(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +#[test] +fn divide_into_dashes_cuts_a_path_into_open_pieces_keeping_its_look() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + // 30 + 10 + 30 + 10 + 20: the gaps are left empty. + let pieces = ids(&r); + assert_eq!((pieces.len(), r["dashes"].clone()), (3, json!(3))); + let st = s.doc().unwrap(); + let spans: Vec<(f64, f64)> = pieces.iter().map(|id| path(&s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect(); + let want = [(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]; + assert!(spans.iter().zip(want).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{spans:?}"); + assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.stroke_width() == 3.0), "the stroke stays"); + assert_eq!(st.selection.objects, pieces); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, l).anchor_count(), 2); + // Kept gaps; fitted 25s with no gap. + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10, "removeGaps": false})).unwrap(); + assert_eq!((ids(&r).len(), r["dashes"].clone()), (5, json!(3))); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "fit": true})).unwrap(); + let spans: Vec = ids(&r).iter().map(|id| path(&s, *id).bounds().unwrap().width()).collect(); + assert_eq!(spans.len(), 3); + assert!(spans.iter().all(|w| (w - 100.0 / 3.0).abs() < 1e-6), "{spans:?}"); +} + +#[test] +fn divide_into_dashes_divides_only_the_selected_segments() { + let mut s = session(); + let u = line(&mut s, &[(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (0.0, 40.0)], false); + // The middle side, between anchors 1 and 2. + select_anchors(&mut s, u, &[1, 2]); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 10})).unwrap(); + let pieces = ids(&r); + assert_eq!((pieces.len(), r["dashes"].clone()), (6, json!(4)), "the first side, four dashes, the last side"); + assert_eq!(path(&s, pieces[0]).bounds().unwrap().width(), 40.0); + let layer: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, pieces, "in the path's place, in order"); +} + +#[test] +fn divide_into_dashes_refuses_bad_params_and_too_many_pieces() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false); + select(&mut s, &[l]); + refuses( + &mut s, + "addon.pathtools.divideDashes", + &[ + json!({"dash": 0}), + json!({"dash": -5}), + json!({"dash": 1e308}), + json!({"dash": "10"}), + json!({"gap": -1}), + json!({"gap": 2e6}), + json!({"fit": "yes"}), + json!({"removeGaps": 1}), + json!({"dash": 0.5}), + ], + ); + // 200000 pieces refused above; 1000 is fine. + assert_eq!(s.execute("addon.pathtools.divideDashes", &json!({"dash": 100})).unwrap()["dashes"], json!(1000)); + s.execute("select.none", &json!({})).unwrap(); + refuses(&mut s, "addon.pathtools.divideDashes", &[json!({})]); +} + +/// The dashes made of `r`'s ids: (first x, last x) of each, by its anchors. +fn dash_spans(s: &Session, r: &Value) -> Vec<(f64, f64)> { + ids(r).iter().map(|id| path(s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect() +} + +fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6) +} + +#[test] +fn expand_dashes_makes_an_open_path_of_each_dash_keeping_the_stroke() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3, "cap": "round", "dash": [30, 10]})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert!(near(&dash_spans(&s, &r), &[(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]), "{:?}", dash_spans(&s, &r)); + assert_eq!(r["dashes"], json!(3)); + let st = s.doc().unwrap(); + for id in ids(&r) { + let node = st.doc.node(id).unwrap(); + let stroke = node.appearance.stroke().unwrap(); + assert_eq!((stroke.width, stroke.cap, stroke.dash.clone()), (3.0, vectorcraft_doc::LineCap::Round, None), "the stroke stays, dashes off"); + assert!(!path(&s, id).subpaths[0].closed); + } + assert_eq!(st.selection.objects, ids(&r)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(l).unwrap().appearance.stroke().unwrap().dash.is_some()); + // The offset shifts the pattern as the stroke draws it: 20 into the first dash. + s.execute("stroke.set", &json!({"dashOffset": 20})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({"ids": [l.0]})).unwrap(); + assert!(near(&dash_spans(&s, &r), &[(0.0, 10.0), (20.0, 50.0), (60.0, 90.0)]), "{:?}", dash_spans(&s, &r)); +} + +#[test] +fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() { + let mut s = session(); + let rect = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap()); + select(&mut s, &[rect]); + s.execute("stroke.set", &json!({"dash": [20, 20]})).unwrap(); + let had_fill = !s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint().is_none(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + // 320 round: eight dashes of 20, a dash bending round each corner it meets. + let pieces = ids(&r); + assert_eq!(pieces.len(), 8); + let st = s.doc().unwrap(); + let layer: Vec = st.doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + if had_fill { + let kept = st.doc.node(rect).unwrap(); + assert!(kept.appearance.stroke().is_none() && kept.appearance.fill().is_some(), "the fill stays on the rectangle"); + assert_eq!(layer, [vec![rect], pieces.clone()].concat(), "the fill below its dashes"); + } else { + assert_eq!(layer, pieces); + } + assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.fill().is_none()), "an open dash isn't filled"); + s.execute("edit.undo", &json!({})).unwrap(); + // Aligned to corners: a dash centred on each corner, the four sides each starting and ending + // on half a dash; 12 dashes along the sides. + s.execute("stroke.set", &json!({"dash": [10, 10], "alignDashes": true})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0)]; + let mut centred = 0; + for id in ids(&r) { + let sp = path(&s, id).subpaths[0].clone(); + if let [a, b, c] = sp.anchors.as_slice() + && corners.iter().any(|k| b.p.distance(*k) < 1e-6) + { + assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}"); + centred += 1; + } + } + assert_eq!((ids(&r).len(), centred), (16, 4)); +} + +#[test] +fn expand_dashes_turns_dots_into_paths_on_their_point_and_releases_compound_paths() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("stroke.set", &json!({"dash": [0, 20], "cap": "round"})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + assert_eq!(ids(&r).len(), 6, "a dot every 20 from 0 to 100"); + assert!(ids(&r).iter().all(|id| path(&s, *id).bounds().unwrap().width() == 0.0)); + s.execute("edit.undo", &json!({})).unwrap(); + // Under a butt cap a dot paints nothing, so there is nothing to expand. + s.execute("stroke.set", &json!({"cap": "butt"})).unwrap(); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + // A compound path's dashes are paths of their own with its stroke. + let a = line(&mut s, &[(0.0, 100.0), (50.0, 100.0)], false); + let b = line(&mut s, &[(0.0, 120.0), (50.0, 120.0)], false); + select(&mut s, &[a, b]); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + s.execute("stroke.set", &json!({"weight": 2, "dash": [20, 10], "cap": "butt"})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + // Each 50 line: 20, gap, 20. + let st = s.doc().unwrap(); + assert_eq!(ids(&r).len(), 4); + for id in ids(&r) { + let n = st.doc.node(id).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "a plain path"); + assert_eq!(n.appearance.stroke_width(), 2.0); + assert!(n.appearance.stroke().unwrap().dash.is_none()); + } + assert!(st.doc.node(c).is_none_or(|n| n.appearance.stroke().is_none()), "the compound path's dashes are gone from it"); +} + +#[test] +fn expand_dashes_refuses_without_dashes_and_past_the_limit() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + select(&mut s, &[l]); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({}), json!({"ids": "x"}), json!({"zzz": 1})]); + // 125000 dashes refused; 1000 are fine. + s.execute("stroke.set", &json!({"dash": [0.4, 0.4]})).unwrap(); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + s.execute("stroke.set", &json!({"dash": [50, 50]})).unwrap(); + assert_eq!(s.execute("addon.pathtools.expandDashes", &json!({})).unwrap()["dashes"], json!(1000)); +} diff --git a/crates/engine/src/cmd/addons/pen.rs b/crates/engine/src/cmd/addons/pen.rs new file mode 100644 index 0000000000..35d0ea5b5d --- /dev/null +++ b/crates/engine/src/cmd/addons/pen.rs @@ -0,0 +1,349 @@ +//! Smart Pen (`addon.pen.*`), a built-in add-on: one tool that draws paths and edits their points, +//! handles and segments without switching tools, and a panel. The commands here are what the tool +//! and the panel do that the standard path commands don't: anchors added with a straight or curved +//! segment into them, segments switched between straight and curved, anchors removed with or +//! without refitting their neighbours, smooth/corner toggles, segments bent by a dragged point, and +//! the panel's next-segment choice and Close or Join. The tool, panel and submenu (Object › +//! Plug-ins › Smart Pen) are the tools crate's and the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::BTreeSet; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{Anchor, AnchorKind, Point, SubPath, Vec2}; +use vectorcraft_pathops::addons::{self as po, pathtools as pt, pen}; +use vectorcraft_tools::addons::smart_pen; + +use super::super::draw2::usize_opt; +use super::super::path::{compound_or_self, join, path_mut}; +use super::super::{CommandSpec, always, bad, checked_id, cmd, finite_numbers, has_doc, has_selection, number_or, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// The largest coordinate or move (pt) the commands take. +const LIMIT: f64 = 1e9; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.pen.append", + "Smart Pen", + [], + None, + "{id, subpath?: index (default: the last open subpath), x, y, in?: [x, y], out?: [x, y], segment?: \"straight\" (the segment into the new anchor is a line: the previous anchor's handle on it goes, and the new anchor's incoming one)|\"curved\" (the previous anchor gets a handle on it if it has none: in line with its other handle, or with a straight segment before it)} add an anchor at the end of an open subpath of path id (default: the handles as given, the previous anchor as it is), as one undo step; the new anchor is selected → {anchor}", + has_doc, + append + ), + cmd!( + "addon.pen.close", + "Close Path", + [], + None, + "{id, subpath?: index (default: the last open subpath), segment?: \"straight\"|\"curved\" (default: the closing segment takes the handles its ends have)} close an open subpath of two anchors or more, as one undo step", + has_doc, + close + ), + cmd!( + "addon.pen.segment", + "Straight or Curved Segment", + [], + None, + "{id, subpath?: index (0), segment: index, curved: bool} make a segment straight (its handles retracted) or curved (each end without a handle on it gets one, in line with its other handle or with a straight segment before it), as one undo step → {changed}", + has_doc, + segment + ), + cmd!( + "addon.pen.removePoint", + "Remove Points, Keep Shape", + [], + None, + "{id, subpath?: index (0), anchor: index, plain?: bool (false: the handles beside it are refitted so the outline keeps its shape, and an open end takes its segment with it; true: it goes and the handles beside it stay as they are)} remove one anchor, as one undo step; a subpath keeps two anchors (three when closed)", + has_doc, + remove_point + ), + cmd!( + "addon.pen.togglePoint", + "Convert Anchor Point", + [], + None, + "{id, subpath?: index (0), anchor: index, ratio?: 0.1..0.5 (0.3905)} a smooth anchor becomes a corner with its handles where they are; any other anchor is made smooth by the auto-smooth rule (a lone handle mirrored; without handles both at right angles to the bisector of the angle at it, ratio × the nearer neighbour's distance long). One undo step → {smooth}", + has_doc, + toggle_point + ), + cmd!( + "addon.pen.reshape", + "Reshape Segment", + [], + None, + "{id, subpath?: index (0), segment: index, t?: 0..1 (where it was grabbed, 0.5; held to 0.05..0.95), dx, dy: pt, mode?: \"free\" (both handles move, the one nearer the grab more)|\"keepAngles\" (each handle keeps its direction)|\"symmetric\" (both handles at right angles to the chord, at one length) (\"free\")} bend a segment so the point grabbed moves by (dx, dy); missing handles grow out of their anchors and a smooth anchor stays smooth. One undo step", + has_doc, + reshape + ), + cmd!( + "addon.pen.nextSegment", + "Next Segment", + ["Object", "Plug-ins", "Smart Pen"], + None, + "{curved: bool} whether a click with the Smart Pen Tool adds a curved segment or a straight one (the tool's `next` option, kept with the preferences) → {next: \"straight\"|\"curved\"}", + always, + next_segment + ), + cmd!( + "addon.pen.closeJoin", + "Close or Join", + ["Object", "Plug-ins", "Smart Pen"], + None, + "{} with exactly two open path ends direct-selected, join them as path.join does; else close the selected open paths keeping their ends' handles, as addon.pathtools.close does. One undo step", + has_selection, + close_join + ), + ] +} + +/// The `segment` param: straight (false) or curved (true), `None` when not given. +fn segment_kind(p: &Value, cmd: &str) -> Result> { + match text_param(p, "segment", cmd)? { + None => Ok(None), + Some("straight") => Ok(Some(false)), + Some("curved") => Ok(Some(true)), + Some(_) => Err(bad(cmd, "`segment` must be \"straight\" or \"curved\"")), + } +} + +/// An index param that must be given. +fn index_req(p: &Value, key: &str, cmd: &str) -> Result { + usize_opt(p, key, cmd)?.ok_or_else(|| bad(cmd, format!("missing integer `{key}`"))) +} + +/// A true or false param that must be given. +fn switch_req(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).and_then(Value::as_bool).ok_or_else(|| bad(cmd, format!("`{key}` must be true or false"))) +} + +/// Two number params that must be given, finite and within [`LIMIT`]. +fn pair(p: &Value, (a, b): (&str, &str), cmd: &str) -> Result<(f64, f64)> { + let (x, y) = (number_or(p, a, f64::NAN, cmd)?, number_or(p, b, f64::NAN, cmd)?); + if !(x.abs() < LIMIT && y.abs() < LIMIT) { + return Err(bad(cmd, format!("give `{a}` and `{b}`"))); + } + Ok((x, y)) +} + +/// The subpath a request names: its path (`id`, editable), its index (`subpath`; without one the +/// last open subpath with `open`, else the first) and its data. +fn subpath_of(s: &Session, p: &Value, cmd: &str, open: bool) -> Result<(NodeId, usize, SubPath)> { + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), cmd)?; + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(cmd, "the path is locked or hidden")); + } + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(cmd, "`id` is not a path"))?; + let si = match usize_opt(p, "subpath", cmd)? { + Some(si) => si, + None if open => path.subpaths.iter().rposition(|sp| !sp.closed).ok_or_else(|| bad(cmd, "the path has no open subpath"))?, + None => 0, + }; + let sp = path.subpaths.get(si).ok_or_else(|| bad(cmd, "no such subpath"))?; + Ok((id, si, sp.clone())) +} + +/// What the selection becomes once a subpath is edited. +enum Pick { + /// As it was (no anchor moved to another index). + Keep, + /// The path (its compound path) selected whole. + Whole, + /// Only this anchor of the subpath, direct-selected. + Anchor(usize), +} + +/// Put `sp` in place of subpath `si` of path `id`, as one undo step labelled `label`. +fn put(s: &mut Session, label: &str, id: NodeId, si: usize, sp: SubPath, pick: Pick) -> Result<()> { + s.edit(label, |d, sel| { + let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + *slot = sp; + let top = compound_or_self(d, id); + match pick { + Pick::Keep => {} + Pick::Whole => sel.set([top]), + Pick::Anchor(ai) => { + sel.set([top]); + sel.anchors.insert(id, BTreeSet::from([(si, ai)])); + } + } + Ok(()) + }) +} + +/// An optional `[x, y]` param, finite and within [`LIMIT`]. +fn point_opt(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => finite_numbers::<2>(v) + .filter(|[x, y]| x.abs() < LIMIT && y.abs() < LIMIT) + .map(|[x, y]| Some(Point::new(x, y))) + .ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y]"))), + } +} + +fn append(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.append"; + let (x, y) = pair(p, ("x", "y"), C)?; + let at = Point::new(x, y); + let (h_in, h_out) = (point_opt(p, "in", C)?.unwrap_or(at), point_opt(p, "out", C)?.unwrap_or(at)); + let curved = segment_kind(p, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, true)?; + if sp.closed { + return Err(bad(C, "the subpath is closed")); + } + sp.anchors.push(Anchor::with_handles(at, h_in, h_out)); + let k = sp.anchors.len() - 1; + if let Some(prev) = k.checked_sub(1) { + match curved { + Some(true) => { + pen::leave_handle(&mut sp, prev, true, pt::SMOOTH_RATIO); + } + Some(false) => { + pen::straighten_segment(&mut sp, prev); + } + None => {} + } + } + put(s, "Smart Pen", id, si, sp, Pick::Anchor(k))?; + Ok(json!({ "anchor": k })) +} + +fn close(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.close"; + let curved = segment_kind(p, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, true)?; + if sp.closed || sp.anchors.len() < 2 { + return Err(bad(C, "the subpath is closed or too short to close")); + } + sp.closed = true; + let last = sp.anchors.len() - 1; + match curved { + Some(true) => { + pen::curve_segment(&mut sp, last, pt::SMOOTH_RATIO); + } + Some(false) => { + pen::straighten_segment(&mut sp, last); + } + None => {} + } + put(s, "Close Path", id, si, sp, Pick::Whole)?; + Ok(json!({})) +} + +fn segment(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.segment"; + let seg = index_req(p, "segment", C)?; + let curved = switch_req(p, "curved", C)?; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + if seg >= sp.segment_count() { + return Err(bad(C, "no such segment")); + } + let changed = if curved { pen::curve_segment(&mut sp, seg, pt::SMOOTH_RATIO) } else { pen::straighten_segment(&mut sp, seg) }; + if changed { + put(s, "Smart Pen", id, si, sp, Pick::Keep)?; + } + Ok(json!({ "changed": changed })) +} + +fn remove_point(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.removePoint"; + let ai = index_req(p, "anchor", C)?; + let plain = switch_or(p, "plain", false, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + let n = sp.anchors.len(); + if ai >= n { + return Err(bad(C, "no such anchor")); + } + let end = !sp.closed && (ai == 0 || ai + 1 == n); + let removed = if plain { + pen::delete_anchor(&mut sp, ai) + } else if let Some((out, _)) = po::remove_anchor_keep_shape(&sp, ai) { + sp = out; + true + } else { + // An open end takes its segment with it. + end && n > 2 && vectorcraft_pathops::remove_anchor(&mut sp, ai) + }; + if !removed { + return Err(bad(C, "the path is too short to remove a point from")); + } + let label = if plain { "Delete Anchor Point" } else { "Remove Points, Keep Shape" }; + put(s, label, id, si, sp, Pick::Whole)?; + Ok(json!({})) +} + +fn toggle_point(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.togglePoint"; + let ai = index_req(p, "anchor", C)?; + let r = super::pathtools::ratio(p, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + if ai >= sp.anchors.len() { + return Err(bad(C, "no such anchor")); + } + let changed = pen::toggle_smooth(&mut sp, ai, r); + let smooth = sp.anchors.get(ai).is_some_and(|a| a.kind == AnchorKind::Smooth); + if changed { + put(s, "Convert Anchor Point", id, si, sp, Pick::Keep)?; + } + Ok(json!({ "smooth": smooth })) +} + +fn reshape(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.reshape"; + let seg = index_req(p, "segment", C)?; + let t = number_or(p, "t", 0.5, C)?; + if !(0.0..=1.0).contains(&t) { + return Err(bad(C, "`t` must be from 0 to 1")); + } + let (dx, dy) = pair(p, ("dx", "dy"), C)?; + let dv = Vec2::new(dx, dy); + let mode = match text_param(p, "mode", C)? { + None => po::ReshapeMode::Free, + Some(m) => po::ReshapeMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"free\", \"keepAngles\" or \"symmetric\""))?, + }; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + if seg >= sp.segment_count() { + return Err(bad(C, "no such segment")); + } + if !po::reshape_segment(&mut sp, seg, t, dv, mode) { + return Err(bad(C, "the segment can't be bent that far")); + } + put(s, "Reshape Segment", id, si, sp, Pick::Keep)?; + Ok(json!({})) +} + +fn next_segment(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.nextSegment"; + let curved = switch_req(p, "curved", C)?; + let next = if curved { "curved" } else { "straight" }; + let values = Map::from_iter([("next".to_string(), json!(next))]); + s.set_tool_options(Some(smart_pen::ID), &values); + Ok(json!({ "next": next })) +} + +fn close_join(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let d = &st.doc; + // The direct-selected anchors that are ends of open subpaths. + let mut picked = 0; + let mut ends = 0; + for (id, set) in &st.selection.anchors { + let path = d.node(*id).and_then(|n| n.path_data()); + for &(si, ai) in set { + picked += 1; + let sp = path.and_then(|pd| pd.subpaths.get(si)); + ends += usize::from(sp.is_some_and(|sp| !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()))); + } + } + if picked == 2 && ends == 2 { + return join(s, &json!({})); + } + super::pathtools::close(s, &json!({ "mode": "handles" })) +} diff --git a/crates/engine/src/cmd/addons/pen/tests.rs b/crates/engine/src/cmd/addons/pen/tests.rs new file mode 100644 index 0000000000..1bb9f3345e --- /dev/null +++ b/crates/engine/src/cmd/addons/pen/tests.rs @@ -0,0 +1,287 @@ +//! Smart Pen's commands: each one undo step, bad params refused, and the tool's gestures through +//! the session. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{AnchorKind, PathData, Point, Vec2}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::{Session, ViewInfo}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId { + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()) +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +fn parallel(a: Vec2, b: Vec2) -> bool { + a.cross(b).abs() < 1e-9 && a.dot(b) > 0.0 +} + +#[test] +fn append_adds_a_straight_or_curved_segment() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 100.0), (100.0, 100.0)]); + let n = steps(&s); + let r = s.execute("addon.pen.append", &json!({"id": id.0, "x": 150, "y": 150, "segment": "curved"})).unwrap(); + assert_eq!(r["anchor"], json!(2)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let sp = &path(&s, id).subpaths[0]; + // The curve leaves (100, 100) along the straight segment before it. + let a = sp.anchors[1]; + assert!(a.has_out() && !a.has_in() && parallel(a.h_out - a.p, Vec2::new(1.0, 0.0)), "{a:?}"); + assert!(sp.segment_is_line(0) && !sp.segment_is_line(1)); + // The new anchor is the one selected. + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.anchors.get(&id), Some(&BTreeSet::from([(0, 2)]))); + // Straight: the previous anchor's handle on it goes, and the new anchor's incoming one. + s.execute("addon.pen.append", &json!({"id": id.0, "subpath": 0, "x": 250, "y": 150, "in": [200, 100], "out": [300, 200], "segment": "straight"})) + .unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.segment_is_line(2) && sp.anchors[3].has_out() && !sp.anchors[3].has_in()); + assert_eq!(sp.anchors[3].kind, AnchorKind::Corner); + // Without a segment, the handles as given. + s.execute("addon.pen.append", &json!({"id": id.0, "x": 350, "y": 150, "in": [330, 140], "out": [370, 160]})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors[4].kind, AnchorKind::Smooth); + let closed = line(&mut s, &[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]); + s.execute("path.close", &json!({"id": closed.0})).unwrap(); + refuses( + &mut s, + "addon.pen.append", + &[ + json!({}), + json!({"id": id.0}), + json!({"id": id.0, "x": 1, "y": f64::MAX}), + json!({"id": id.0, "x": 1, "y": 1, "segment": "wavy"}), + json!({"id": id.0, "x": 1, "y": 1, "in": [1]}), + json!({"id": id.0, "x": 1, "y": 1, "subpath": 3}), + json!({"id": closed.0, "x": 1, "y": 1}), + json!({"id": closed.0, "x": 1, "y": 1, "subpath": 0}), + json!({"id": 999_999, "x": 1, "y": 1}), + ], + ); +} + +#[test] +fn close_makes_the_closing_segment_straight_or_curved() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]); + let n = steps(&s); + s.execute("addon.pen.close", &json!({"id": id.0, "segment": "curved"})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed && !sp.segment_is_line(2)); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pen.close", &json!({"id": id.0, "segment": "straight"})).unwrap(); + assert!(path(&s, id).subpaths[0].segment_is_line(2)); + let dot = line(&mut s, &[(5.0, 5.0)]); + refuses(&mut s, "addon.pen.close", &[json!({}), json!({"id": id.0}), json!({"id": dot.0}), json!({"id": id.0, "segment": 1})]); +} + +#[test] +fn segment_switches_between_straight_and_curved() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]); + let n = steps(&s); + let r = s.execute("addon.pen.segment", &json!({"id": id.0, "segment": 1, "curved": true})).unwrap(); + assert_eq!(r["changed"], json!(true)); + assert!(!path(&s, id).subpaths[0].segment_is_line(1)); + s.execute("addon.pen.segment", &json!({"id": id.0, "segment": 1, "curved": false})).unwrap(); + assert!(path(&s, id).subpaths[0].segment_is_line(1)); + assert_eq!(steps(&s), n + 2); + // Already straight: no step. + let r = s.execute("addon.pen.segment", &json!({"id": id.0, "segment": 1, "curved": false})).unwrap(); + assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), n + 2)); + refuses( + &mut s, + "addon.pen.segment", + &[ + json!({"id": id.0, "segment": 1}), + json!({"id": id.0, "segment": 2, "curved": true}), + json!({"id": id.0, "curved": true}), + json!({"id": id.0, "segment": -1, "curved": true}), + ], + ); +} + +#[test] +fn remove_point_keeps_the_shape_or_deletes_plainly() { + let mut s = session(); + let e = NodeId(s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + let before = path(&s, e); + let n = steps(&s); + s.execute("addon.pen.removePoint", &json!({"id": e.0, "anchor": 1})).unwrap(); + let after = path(&s, e); + assert_eq!(after.anchor_count(), 7); + assert_eq!(steps(&s), n + 1); + // The outline barely moved: its bounds are the circle's. + let (b0, b1) = (before.bounds().unwrap(), after.bounds().unwrap()); + assert!((b0.width() - b1.width()).abs() < 2.0 && (b0.height() - b1.height()).abs() < 2.0, "{b0:?} {b1:?}"); + // Plain: the handles beside it stay as they were. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pen.removePoint", &json!({"id": e.0, "anchor": 1, "plain": true})).unwrap(); + let plain = path(&s, e); + assert_eq!( + (plain.subpaths[0].anchors[0].h_out, plain.subpaths[0].anchors[1].h_in), + (before.subpaths[0].anchors[0].h_out, before.subpaths[0].anchors[2].h_in) + ); + // An open end goes with its segment; two anchors stay. + let l = line(&mut s, &[(0.0, 0.0), (50.0, 0.0), (100.0, 0.0)]); + s.execute("addon.pen.removePoint", &json!({"id": l.0, "anchor": 2})).unwrap(); + assert_eq!(path(&s, l).subpaths[0].anchors.len(), 2); + refuses( + &mut s, + "addon.pen.removePoint", + &[ + json!({"id": l.0, "anchor": 0}), + json!({"id": l.0, "anchor": 0, "plain": true}), + json!({"id": l.0, "anchor": 5}), + json!({"id": l.0}), + json!({"id": l.0, "anchor": 1, "plain": 1}), + ], + ); +} + +#[test] +fn toggle_point_and_reshape() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]); + let n = steps(&s); + assert_eq!(s.execute("addon.pen.togglePoint", &json!({"id": id.0, "anchor": 1})).unwrap()["smooth"], json!(true)); + let smooth = path(&s, id).subpaths[0].anchors[1]; + assert_eq!(s.execute("addon.pen.togglePoint", &json!({"id": id.0, "anchor": 1})).unwrap()["smooth"], json!(false)); + let corner = path(&s, id).subpaths[0].anchors[1]; + assert_eq!((corner.h_in, corner.h_out), (smooth.h_in, smooth.h_out), "nothing moved"); + assert_eq!(steps(&s), n + 2); + refuses(&mut s, "addon.pen.togglePoint", &[json!({"id": id.0, "anchor": 9}), json!({"id": id.0, "anchor": 1, "ratio": 2})]); + // The grabbed point follows the drag. + let l = line(&mut s, &[(0.0, 200.0), (100.0, 200.0)]); + for mode in ["free", "keepAngles", "symmetric"] { + s.execute("addon.pen.reshape", &json!({"id": l.0, "segment": 0, "t": 0.5, "dx": 0, "dy": -40, "mode": mode})).unwrap(); + let p = kurbo::ParamCurve::eval(&path(&s, l).subpaths[0].segment(0), 0.5); + assert!(p.distance(Point::new(50.0, 160.0)) < 1e-6, "{mode}: {p:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + refuses( + &mut s, + "addon.pen.reshape", + &[ + json!({"id": l.0, "segment": 0}), + json!({"id": l.0, "segment": 1, "dx": 1, "dy": 1}), + json!({"id": l.0, "segment": 0, "dx": 1, "dy": 1, "t": 2}), + json!({"id": l.0, "segment": 0, "dx": 1e300, "dy": 1}), + json!({"id": l.0, "segment": 0, "dx": 1, "dy": 1, "mode": "twist"}), + ], + ); +} + +#[test] +fn the_panel_commands_set_the_next_segment_and_close_or_join() { + let mut s = session(); + assert_eq!(s.execute("addon.pen.nextSegment", &json!({"curved": true})).unwrap()["next"], json!("curved")); + assert_eq!(s.tool_options_of("smartPen")["next"], json!("curved")); + assert!(s.execute("addon.pen.nextSegment", &json!({})).is_err()); + // Two open ends direct-selected: joined. + let a = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)]); + let b = line(&mut s, &[(110.0, 0.0), (200.0, 0.0)]); + s.select(|_, sel| { + sel.set([a, b]); + sel.anchors.insert(a, BTreeSet::from([(0, 1)])); + sel.anchors.insert(b, BTreeSet::from([(0, 0)])); + }) + .unwrap(); + let n = steps(&s); + s.execute("addon.pen.closeJoin", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + assert!(s.doc().unwrap().doc.node(b).is_none() || s.doc().unwrap().doc.node(a).is_none(), "one path is left"); + // Otherwise the selected open paths close. + let c = line(&mut s, &[(0.0, 100.0), (100.0, 100.0), (100.0, 200.0)]); + s.execute("addon.pen.closeJoin", &json!({})).unwrap(); + assert!(path(&s, c).subpaths[0].closed); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +/// A gesture of the active tool, `m` held throughout: press at the first point, drag through the +/// others, release at the last. +fn gesture(s: &mut Session, pts: &[(f64, f64)], m: Mods) { + let mut kinds = vec![PointerKind::Down]; + kinds.extend(pts.iter().skip(1).map(|_| PointerKind::Drag)); + for (k, (x, y)) in kinds.into_iter().zip(pts.iter().copied()) { + s.pointer(&PointerEvent::new(k, x, y).with_mods(m), view()).unwrap(); + } + let (x, y) = pts.last().copied().unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(m), view()).unwrap(); +} + +/// The one path of the session's document. +fn only_path(s: &Session) -> (NodeId, PathData) { + let mut found = vec![]; + s.doc().unwrap().doc.walk(|n| { + if let Some(p) = n.path_data() { + found.push((n.id, p.clone())); + } + }); + assert_eq!(found.len(), 1, "{found:?}"); + found.remove(0) +} + +#[test] +fn the_tool_draws_a_path_one_step_per_anchor_and_closes_it() { + let mut s = session(); + s.select_tool("smartPen", view()).unwrap(); + let n = steps(&s); + gesture(&mut s, &[(50.0, 50.0)], Mods::default()); + gesture(&mut s, &[(150.0, 50.0)], Mods::default()); + s.execute("addon.pen.nextSegment", &json!({"curved": true})).unwrap(); + gesture(&mut s, &[(150.0, 150.0)], Mods::default()); + let (id, p) = only_path(&s); + let sp = &p.subpaths[0]; + assert_eq!(sp.anchors.len(), 3); + assert!(sp.segment_is_line(0) && !sp.segment_is_line(1), "a straight segment, then a curved one leaving it tangent"); + assert!(parallel(sp.anchors[1].h_out - sp.anchors[1].p, Vec2::new(1.0, 0.0))); + // A drag makes a smooth anchor. + gesture(&mut s, &[(50.0, 150.0), (30.0, 170.0)], Mods::default()); + assert_eq!(path(&s, id).subpaths[0].anchors[3].kind, AnchorKind::Smooth); + // Tab between anchors: the last segment straight again. + s.tool_key(ToolKey::Tab, Mods::default(), view()).unwrap(); + assert!(path(&s, id).subpaths[0].segment_is_line(2)); + gesture(&mut s, &[(50.0, 50.0)], Mods::default()); + assert!(path(&s, id).subpaths[0].closed); + assert_eq!(steps(&s), n + 6, "one step per anchor, the Tab and the close"); + // Edits with the same tool: a drag on an anchor moves it, Alt-click removes one keeping the shape. + s.select(|_, sel| sel.set([id])).unwrap(); + gesture(&mut s, &[(150.0, 50.0), (160.0, 40.0)], Mods::default()); + assert_eq!(path(&s, id).subpaths[0].anchors[1].p, Point::new(160.0, 40.0)); + gesture(&mut s, &[(160.0, 40.0)], Mods { alt: true, ..Mods::default() }); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3); + assert_eq!(steps(&s), n + 8); +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index c52b0003ff..33379e752e 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -27,7 +27,7 @@ use vectorcraft_doc::appearance::SharedStack; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; use vectorcraft_geom::Rect; -use super::edit::{outermost, selected_roots}; +use super::edit::{outermost, roots_of, selected_roots}; use super::opacitymask::percent; use super::paint::paint_from; use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs}; @@ -44,7 +44,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{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)", + "{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). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill is a copy of that row, right above it, and becomes the active row", has_doc, |s, p| add_item(s, p, true) ), @@ -71,7 +71,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only the topmost visible fill and stroke, without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects", has_doc, reduce_basic ), @@ -125,7 +125,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}", has_doc, copy_from ), @@ -255,17 +255,36 @@ impl ItemTarget { if fits == Some(true) { self } else { ItemTarget::Top } } - /// This target for each of `ids` in `d` (in their order): an aligned item (a row of the first - /// target's stack) is, in each other target, the item equal to it there (see + /// This target for each of `ids` (in their order): an aligned item (a row of the first + /// target's stack, or for the active item of the first selected object's, see + /// [`ItemTarget::anchor`]) is, in each other target, the item equal to it there (see /// [`SharedStack`]); `None` for a target that has none, which the edit leaves alone. A row the /// targets don't share, and any other target, stands for itself in every target. - pub(crate) fn per_target(self, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec> { + pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec> { let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; - let Some(shared) = shared_stack(d, ids) else { return vec![Some(self); ids.len()] }; + let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] }; + let k = self.anchor(s, ids); + let mut order = ids.to_vec(); + order.swap(0, k); + let Some(shared) = shared_stack(&st.doc, &order) else { return vec![Some(self); ids.len()] }; if !shared.has_item(index) { return vec![Some(self); ids.len()]; } - (0..ids.len()).map(|k| shared.item_in(index, k).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect() + let mut per: Vec> = + (0..order.len()).map(|j| shared.item_in(index, j).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect(); + per.swap(0, k); + per + } + + /// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of + /// is: the first selected object (or the compound path holding it) for the active item, which + /// need not paint first; the first target otherwise, or when that object is not among them. + pub(crate) fn anchor(self, s: &Session, ids: &[NodeId]) -> usize { + let ItemTarget::Item { explicit: false, .. } = self else { return 0 }; + let Some(st) = s.active() else { return 0 }; + let Some(first) = st.selection.subjects().first() else { return 0 }; + let root = roots_of(&st.doc, vec![*first]).first().copied().unwrap_or(*first); + ids.iter().position(|id| *id == root).unwrap_or(0) } /// The item of `ap` a fill (`fill`) or stroke edit changes; `None` = the topmost one. @@ -407,7 +426,7 @@ pub(crate) fn edit_items_then( return Ok(()); } let before = s.doc()?.doc.clone(); - let per = item.per_target(&before, ids); + let per = item.per_target(s, ids); super::overprint::edit_counted(s, label, |d| { let mut edited = Vec::new(); for (id, item) in ids.iter().zip(&per) { @@ -429,7 +448,7 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_ } /// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the -/// targeted item (on the first target object), else `default`. A `stroke` other than true, false or +/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or /// null is an error of command `cmd`. pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result { check_switches(p, &["stroke"], cmd)?; @@ -439,7 +458,7 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo let ItemTarget::Item { index, .. } = item else { return Ok(default) }; let ids = appearance_targets(s, p)?; let d = &s.doc()?.doc; - Ok(ids.first().and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) + Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) } /// The whole number of 0 or more that `key` holds, read with [`index`]. @@ -470,12 +489,45 @@ 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(); + // The panel's active Fill row, when the new fill goes on the selection: the new fill is a copy + // of that row, right above it in each target that has it (others get a copy of their top fill). // 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()); + // The active row is a row of the active object's stack, which need not come first in `ids` + // (they are in paint order): match the others against it. + let anchor = active.and_then(|a| ids.iter().position(|id| *id == a)); + let selected = match (s.appearance_item(), anchor) { + (Some(index), Some(_)) if fill && p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? => { + ItemTarget::Item { index, explicit: false, aligned: true }.of_kind(s, true) + } + _ => ItemTarget::Top, + }; + let per: Vec> = match (selected, anchor) { + (ItemTarget::Item { index, .. }, Some(k)) => { + let mut order = ids.clone(); + order.swap(0, k); + let mut per: Vec> = + items_per_target(&s.doc()?.doc, &order, &[index], true).into_iter().map(|v| v.first().copied()).collect(); + per.swap(0, k); + per + } + _ => vec![None; ids.len()], + }; let mut inserted = None; + // Where the new fill went in on the active item's object, when it went above the active row. + let mut above = None; s.edit(if fill { "Add New Fill" } else { "Add New Stroke" }, |d, _| { - for id in &ids { + for (id, row) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { + if let Some(i) = n.appearance.item_of_kind(*row, true) + && let Some(paint) = n.appearance.paint_at(Some(i), true).cloned() + { + n.appearance.insert_item(i + 1, AppearanceItem::Fill(FillLayer::new(paint))); + if active == Some(*id) { + above = Some(i + 1); + } + continue; + } // A copy of the top fill (stroke); without one, type's characters' and otherwise the // default paint, so a new fill on a group or type shows. let paint = match (n.appearance.paint_at(None, fill), &n.kind) { @@ -509,8 +561,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } 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)))); + // A fill added above the active row becomes the active row; otherwise the rows above the new + // item move up by one. + s.remap_appearance_item(&ids, |a| above.or(Some(a + usize::from(inserted.is_some_and(|k| k <= a))))); ok() } @@ -580,11 +633,30 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { let ids = require_targets(s, p, "appearance.reduceToBasic")?; // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // The Appearance panel's active row (a row of the first selected object's stack, and in each + // other target the row equal to it there), when the command acts on that selection. The targets + // are in paint order, so the first selected object can be any of them. + let first = s.doc()?.selection.subjects().first().and_then(|f| ids.iter().position(|id| id == f)); + let active = match (s.appearance_item(), first) { + (Some(index), Some(k)) if p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? => { + let mut from = ids.clone(); + from.swap(0, k); + let mut rows = items_per_target(&before, &from, &[index], true); + rows.swap(0, k); + rows + } + _ => vec![Vec::new(); ids.len()], + }; super::overprint::edit_counted(s, "Reduce to Basic Appearance", |d| { - for id in &ids { + for (id, at) in ids.iter().zip(&active) { if let Some(n) = d.node_mut(*id) { - // The topmost visible fill and stroke stay, without their own transparency or effects. - let top = |fill: bool| n.appearance.items.iter().rev().find(|i| i.visible() && i.is_fill() == fill).cloned(); + // The active row stays when it is a visible fill or stroke; otherwise the topmost + // visible one of each kind does. Both lose their own transparency and effects. + let picked = at.first().and_then(|i| n.appearance.items.get(*i)).filter(|i| i.visible()).cloned(); + let top = |fill: bool| match &picked { + Some(i) if i.is_fill() == fill => Some(i.clone()), + _ => n.appearance.items.iter().rev().find(|i| i.visible() && i.is_fill() == fill).cloned(), + }; let (fill, stroke) = (top(true), top(false)); // Other objects always keep a fill row (None when there was none); a group only // keeps the rows it had. @@ -840,11 +912,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { const C: &str = "appearance.copyFrom"; let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?; let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?); + let defaults_only = switch_or(p, "defaultsOnly", false, C)?; + if defaults_only && (reverse || append || p.get("ids").is_some()) { + return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `reverse` or `append`")); + } let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?; - let range = if !reverse && !append && p.get("ids").is_none() { super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b) } else { None }; - let selected = match ids_param(p, "ids") { - Some(v) => outermost(&s.doc()?.doc, v), - None => selected_roots(s)?, + let range = if !defaults_only && !reverse && !append && p.get("ids").is_none() { + super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b) + } else { + None + }; + let selected = if defaults_only { + vec![] + } else { + match ids_param(p, "ids") { + Some(v) => outermost(&s.doc()?.doc, v), + None => selected_roots(s)?, + } }; // Reversed, the first selected object's attributes go onto the clicked object; with nothing // selected, what the Eyedropper picked up last does (#4382). @@ -864,7 +948,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?, }; let picked = Picked::of(&node); - if !reverse { + if !reverse && !defaults_only { s.eyedropper_sample = Some(node); } let range = range.filter(|(id, _, _)| targets.contains(id)); diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 9bb04dac92..04498111c9 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -335,7 +335,7 @@ fn scatter_shapes() -> BrushLibrary { a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold)))); a }); - doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) }); + doc.symbols.push(Symbol { dynamic: false, name: "Sparkle".into(), art: Arc::new(sparkle) }); let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) }); let random = |a: f64, b: f64| (a, b); let base = Scatter { colorization: Colorization::Tints, ..Default::default() }; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 8ef171d326..7386f77186 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -25,6 +25,7 @@ use super::{ use crate::EngineError; mod brushes; +mod dynamic; mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; @@ -32,10 +33,12 @@ use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; -pub(crate) use symbols::{natural_size, normalize, place_xf, set_natural_size}; +use dynamic::{symbol_instance_reset, symbol_instance_set_appearance}; +use symbols::selected_instances; +pub(crate) use symbols::{fit_instances_of, instance_in_place, instances_of, natural_size, normalize, place_xf, set_natural_size, store_symbol}; use symbols::{ - symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place, - symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_update, + symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace, + symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update, }; const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES; @@ -125,7 +128,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles and graphic styles count, and so do strokes in the art of a brush that is used", + "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do strokes in the art of a brush that is used", has_doc, brush_unused ), @@ -134,7 +137,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%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art). scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, 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%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -157,13 +160,21 @@ pub fn specs() -> Vec { brush_freehand ), // ----- symbols ----- - cmd!(query "symbol.list", "Symbols", [], None, "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic}], current}", has_doc, symbol_list), + cmd!( + query "symbol.list", + "Symbols", + [], + None, + "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}", + has_doc, + symbol_list + ), cmd!( "symbol.new", "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice, type}", has_selection, symbol_new ), @@ -172,7 +183,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array} rename a symbol and/or set Symbol Options › Registration and Export Type and 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1; default name: current) → {name, registration, exportType, nineSlice}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", has_doc, symbol_options ), @@ -190,7 +201,7 @@ pub fn specs() -> Vec { "Break Link to Symbol", [], None, - "{ids?|id?} expand selected instances into plain art → {ids}", + "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol) → {ids}", has_selection, symbol_break_link ), @@ -199,16 +210,25 @@ pub fn specs() -> Vec { "Edit Symbol", [], None, - "{id?, ids?: [id…] (instead of id)} break the link of the selected instance so its art can be edited; finish with symbol.update → {name, ids}", - has_selection, - symbol_edit + "{id?, ids?: [id…] (instead of id), name?, x?, y?, artboard?: index=0 (the active artboard; the app passes it), viewCenter?: [x, y] (the app passes the view's center)} edit a symbol's art in symbol editing mode: the instance `id` (default: the selected instances, which must share one symbol) where it shows the art, else the symbol `name` (default: the current symbol) centered on (x, y) (default: the center of artboard `artboard`, or of the first artboard when there is no such artboard; in a document without artboards, viewCenter, else (0, 0)); every instance follows each edit and the instance stays linked (symbol.breakLink expands one); refused while a pattern or an opacity mask is edited → {name, layer, id?}", + has_doc, + super::symboledit::enter + ), + cmd!( + "symbol.exitEditing", + "Exit Symbol Editing Mode", + [], + None, + "{} leave symbol editing mode; after an edit, select the instance it was entered from; leaving without having changed the art adds no undo step and restores the selection from before entry (object.exitIsolation also leaves it) → {name?}", + has_doc, + super::symboledit::leave ), cmd!( "symbol.update", "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", + "{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", has_selection, symbol_update ), @@ -217,7 +237,7 @@ pub fn specs() -> Vec { "Delete Symbol", [], None, - "{name, expandInstances?: true} delete a symbol; its instances are expanded (or deleted with false)", + "{name | names: [name…], expandInstances?: true} delete a symbol (or several, in one undo step); its instances are expanded (or deleted with false)", has_doc, symbol_delete ), @@ -227,10 +247,28 @@ pub fn specs() -> Vec { "Replace Symbol", [], None, - "{name, ids?|id?} swap the symbol of the selected instances → {ids}", + "{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them) → {ids}", has_selection, symbol_replace ), + cmd!( + "symbol.instance.setAppearance", + "Symbol Instance Appearance", + [], + None, + "{id?|ids?: [one id] (default: the one selected object), path: [i…] (the object in the symbol's art: child indices in paint order from the art's root down through its groups; [] the root), fill?: \"#rrggbb\"|{…paint params of paint.setFill: color, none, swatch, tint, gradient, keepModel}|null (null: the symbol's own again), stroke?: as fill, opacity?: 0..100|null, blend?: name|null} change the appearance of one object of a dynamic symbol instance's art, for that instance only: it stays linked, so editing the symbol reshapes it and keeps the change; refused for a static symbol or a path naming no object → {id, overrides: how many objects the instance changes}", + has_selection, + symbol_instance_set_appearance + ), + cmd!( + "symbol.instance.reset", + "Reset Symbol Instance", + [], + None, + "{ids?|id?} drop the selected dynamic symbol instances' own appearance changes, so they show the symbol's appearance again → {ids: the instances that had changes}", + has_selection, + symbol_instance_reset + ), cmd!( "symbol.setCurrent", "Current Symbol", @@ -240,6 +278,15 @@ pub fn specs() -> Vec { has_doc, symbol_set_current ), + cmd!( + query "symbol.unused", + "Select All Unused", + [], + None, + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + has_doc, + symbol_unused + ), cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances), cmd!( "symbol.spray", diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 66dd546e90..9cc52c82c8 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -362,14 +362,15 @@ fn art_brushes(n: &Node, out: &mut Vec) { } /// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph -/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush -/// that a counted stroke paints with. +/// designs, pattern tiles and the tiles that pattern editing's Cancel puts back, and graphic styles +/// count, and so do the strokes in the art of every brush that a counted stroke paints with. pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result { let d = &s.doc()?.doc; let lib = brush::library(d); let mut todo = vec![]; let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); - trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + trees.chain(patterns.flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo)); let mut used = BTreeSet::new(); while let Some(name) = todo.pop() { @@ -389,7 +390,77 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; let mut v = serde_json::to_value(&lib[i]).unwrap_or_default(); if let Some(params) = p.get("params") { + let original = v.clone(); merge(&mut v, params); + if lib[i].kind.type_id() == "pattern" { + let tiles = [ + ("side_tile", "side"), + ("outer_corner_tile", "outer_corner"), + ("inner_corner_tile", "inner_corner"), + ("start_tile", "start"), + ("end_tile", "end"), + ]; + // Resolve all Original choices against the brush before any tile can clear the art + // another corner borrows. Keep the matching frame with each copied tile. + let originals: Vec<_> = tiles + .iter() + .map(|(_, art)| { + let from = if art.ends_with("corner") + && original.get(art).is_none_or(Value::is_null) + && original.get(if *art == "outer_corner" { "outer_source" } else { "inner_source" }).is_none_or(Value::is_null) + { + if *art == "outer_corner" { "inner_corner" } else { "outer_corner" } + } else { + *art + }; + (original.get(from).cloned().unwrap_or(Value::Null), original.get(format!("{from}_frame")).cloned().unwrap_or(Value::Null)) + }) + .collect(); + for ((tile, art), (original_art, original_frame)) in tiles.into_iter().zip(originals) { + let frame = format!("{art}_frame"); + let swatch = format!("{art}_swatch"); + let Some(choice) = params.get(tile) else { + if params.get(art).is_some() { + if params.get(frame.as_str()).is_none() { + v[frame.as_str()] = Value::Null; + } + if params.get(swatch.as_str()).is_none() { + v[swatch.as_str()] = Value::Null; + } + } + continue; + }; + let (choice, swatch_only) = if let Some(name) = choice.as_object() { + (name.get("pattern").and_then(Value::as_str).ok_or_else(|| bad(C, "invalid pattern tile choice"))?, true) + } else { + (choice.as_str().ok_or_else(|| bad(C, "invalid pattern tile choice"))?, false) + }; + if art == "side" && choice == "none" && !swatch_only { + return Err(bad(C, "You must choose a side pattern.")); + } + if choice == "original" && !swatch_only { + v[art] = original_art; + v[frame.as_str()] = original_frame; + v[swatch.as_str()] = Value::Null; + } else if !swatch_only && (choice == "none" || (art.ends_with("corner") && brush::CornerSource::parse(choice).is_some())) { + v[art] = Value::Null; + v[frame.as_str()] = Value::Null; + v[swatch.as_str()] = Value::Null; + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else { + let pattern = s.doc()?.doc.pattern(choice).ok_or_else(|| bad(C, format!("no pattern named `{choice}`")))?; + let copy = Node::new(NodeId(0), NodeKind::Group { children: pattern.art.clone(), clip: false }); + v[art] = serde_json::to_value(copy).unwrap_or_default(); + v[frame.as_str()] = serde_json::to_value(pattern.tile).unwrap_or_default(); + v[swatch.as_str()] = json!(choice); + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } } let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string); if let Some(nn) = &new_name { diff --git a/crates/engine/src/cmd/brushsym/dynamic.rs b/crates/engine/src/cmd/brushsym/dynamic.rs new file mode 100644 index 0000000000..baa721c45b --- /dev/null +++ b/crates/engine/src/cmd/brushsym/dynamic.rs @@ -0,0 +1,151 @@ +//! Dynamic symbols (Symbol Options › Symbol Type): an instance of a dynamic symbol changes the +//! appearance of objects in the symbol's art and stays linked to the symbol +//! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance +//! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still +//! there ([`fit_overrides`]). + +use std::sync::Arc; + +use vectorcraft_color::BlendMode; +use vectorcraft_doc::symbol_overrides::{self, SymbolOverride}; + +use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, ids_json, json, roots, selected_instances}; + +/// The `type` param, Symbol Options › Symbol Type: `Some(true)` for dynamic. +pub(super) fn type_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("type").filter(|v| !v.is_null()) else { return Ok(None) }; + match v.as_str() { + Some("static") => Ok(Some(false)), + Some("dynamic") => Ok(Some(true)), + _ => Err(bad(cmd, format!("type must be static or dynamic, not {v}"))), + } +} + +/// The `type` a symbol reports. +pub(super) fn type_id(dynamic: bool) -> &'static str { + if dynamic { "dynamic" } else { "static" } +} + +/// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or +/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art. +pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) { + for id in ids { + let art = match d.node(*id) { + Some(n) if !n.extras().symbol_overrides.is_empty() => match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).filter(|s| s.dynamic).map(|s| s.art.clone()), + _ => continue, + }, + _ => continue, + }; + let Some(n) = d.node_mut(*id) else { continue }; + let mut e = n.extras_mut(); + match art { + Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art), + None => e.symbol_overrides.clear(), + } + } +} + +/// The instance `id` names (else the one selected object) and its symbol's art; the symbol must +/// be dynamic. +fn dynamic_instance(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, Arc)> { + let d = &s.doc()?.doc; + let not_one = || EngineError::Other("select a symbol instance".into()); + let [id] = roots(s, p)?[..] else { return Err(not_one()) }; + let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node(id).map(|n| &n.kind) else { return Err(not_one()) }; + let sym = d.symbols.iter().find(|x| x.name == *symbol).ok_or_else(|| bad(cmd, format!("no symbol named `{n}`", n = symbol)))?; + if !sym.dynamic { + let name = &sym.name; + return Err(bad(cmd, format!("`{name}` is a static symbol: set its Symbol Type to Dynamic first"))); + } + Ok((id, sym.art.clone())) +} + +/// The `path` param: child indices from the art's root, naming an object of `art`. +fn path_param(p: &Value, art: &Node, cmd: &str) -> Result> { + let path: Option> = + p.get("path").and_then(Value::as_array).and_then(|a| a.iter().map(|i| i.as_u64().and_then(|i| u32::try_from(i).ok())).collect()); + let path = path.ok_or_else(|| bad(cmd, "path must be a list of child indices"))?; + if symbol_overrides::part(art, &path).is_none() { + let shown = json!(path); + return Err(bad(cmd, format!("no object at path {shown} in the symbol's art"))); + } + Ok(path) +} + +/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or +/// an object of `paint.setFill`'s paint params sets it. +fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result>> { + let Some(v) = p.get(key) else { return Ok(None) }; + if v.is_null() { + return Ok(Some(None)); + } + let v = if v.is_string() { json!({ "color": v }) } else { v.clone() }; + let paint = crate::cmd::paint::paint_from(s, &v)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?; + Ok(Some(Some(paint))) +} + +/// The change `p` asks of the override `old` (for the object at `path`). +fn changed(s: &Session, p: &Value, old: SymbolOverride, cmd: &str) -> Result { + let mut o = old; + if let Some(fill) = paint_change(s, p, "fill", cmd)? { + o.fill = fill; + } + if let Some(stroke) = paint_change(s, p, "stroke", cmd)? { + o.stroke = stroke; + } + check_numbers(p, &["opacity"], cmd)?; + if let Some(v) = p.get("opacity") { + o.opacity = v.as_f64().map(crate::cmd::opacitymask::percent); + } + if let Some(v) = p.get("blend") { + o.blend = match v { + Value::Null => None, + b => Some(b.as_str().and_then(BlendMode::parse).ok_or_else(|| bad(cmd, format!("unknown blend mode {b}")))?), + }; + } + Ok(o) +} + +pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.instance.setAppearance"; + if !["fill", "stroke", "opacity", "blend"].iter().any(|k| p.get(k).is_some()) { + return Err(bad(C, "give fill, stroke, opacity and/or blend")); + } + let (id, art) = dynamic_instance(s, p, C)?; + let path = path_param(p, &art, C)?; + let d = &s.doc()?.doc; + let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned()); + let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?; + let count = s.edit("Symbol Instance Appearance", |d, _| { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let mut e = n.extras_mut(); + let list = &mut e.symbol_overrides; + list.retain(|o| o.path != path); + if !new.is_empty() { + list.push(new); + } + Ok(list.len()) + })?; + Ok(json!({ "id": id.0, "overrides": count })) +} + +pub(super) fn symbol_instance_reset(s: &mut Session, p: &Value) -> Result { + let ids = selected_instances(s, p)?; + if ids.is_empty() { + return Err(EngineError::Other("no symbol instances selected".into())); + } + let d = &s.doc()?.doc; + let changed: Vec = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.extras().symbol_overrides.is_empty())).collect(); + if !changed.is_empty() { + s.edit("Reset Symbol Instance", |d, _| { + for id in &changed { + if let Some(n) = d.node_mut(*id) { + n.extras_mut().symbol_overrides.clear(); + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&changed) })) +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 8e8ba163ee..9bfbb902a7 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,3 +1,4 @@ +use super::dynamic::{fit_overrides, type_id, type_param}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json, @@ -94,7 +95,14 @@ pub(crate) fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> { Ok((art, (w, h), c)) } -fn instances_of(d: &Document, name: Option<&str>) -> Vec { +/// After the art of symbol `name` changed: each of its instances keeps its appearance changes to +/// the objects the art still has. +pub(crate) fn fit_instances_of(d: &mut Document, name: &str) { + let ids = instances_of(d, Some(name)); + fit_overrides(d, &ids); +} + +pub(crate) fn instances_of(d: &Document, name: Option<&str>) -> Vec { let mut v = vec![]; d.walk(|n| { if let NodeKind::SymbolInstance { symbol, .. } = &n.kind @@ -106,6 +114,37 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec { v } +/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`. +fn art_symbols(n: &Node, out: &mut Vec) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if let NodeKind::SymbolInstance { symbol, .. } = &m.kind { + out.push(symbol.clone()); + } + }); +} + +/// Select All Unused (#4918): the symbols nothing places. Instances in the art (opacity masks +/// included), graph designs, pattern tiles and the tiles that pattern editing's Cancel puts back, +/// and the art of the document's brushes count, and so do the instances in the art of every symbol +/// a counted instance places. A symbol placed only inside an unused symbol is unused too. +pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result { + let d = &s.doc()?.doc; + let mut todo = vec![]; + let lib = brush::library(d); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art)); + trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo)); + let mut used = std::collections::BTreeSet::new(); + while let Some(name) = todo.pop() { + if !used.contains(&name) { + d.symbols.iter().filter(|sym| sym.name == name).for_each(|sym| art_symbols(&sym.art, &mut todo)); + used.insert(name); + } + } + let names: Vec<&str> = d.symbols.iter().map(|sym| sym.name.as_str()).filter(|n| !used.contains(*n)).collect(); + Ok(json!({ "names": names })) +} + fn symbol_names(d: &Document) -> Vec { d.symbols.iter().map(|s| s.name.clone()).collect() } @@ -128,12 +167,32 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { "registration": d.symbol_registration(&sym.name).0, "exportType": d.symbol_export_type(&sym.name).id(), "nineSlice": nine_slice_json(d, &sym.name), + "type": type_id(sym.dynamic), }) }) .collect(); Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) } +/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the +/// current symbol. +pub(crate) fn store_symbol(d: &mut Document, art: &Node, name: &str, size: (f64, f64)) { + let art = d.reid(art); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(d, name, Some(size)); + d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); +} + +/// Replace the root nodes `ids` with one instance of symbol `name` (already stored) placed by +/// `xf`. Frames of threaded text among them leave their threads with the text they show. Returns +/// the instance's id. +pub(crate) fn instance_in_place(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result { + let threaded = crate::cmd::threads::frames(d); + let id = replace_with_instance(d, ids, name, xf)?; + crate::cmd::threads::leave_threads(d, &threaded); + Ok(id) +} + /// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id. fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result { let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?; @@ -160,26 +219,29 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER); let export = export_type_param(p, C)?.unwrap_or_default(); let nine = nine_slice_param(p, C, None)?.flatten(); + let dynamic = type_param(p, C)?.unwrap_or(false); // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { - let art = d.reid(&art); - d.symbols.push(Symbol { name: name.clone(), art: Arc::new(art) }); - set_natural_size(d, &name, Some(size)); + store_symbol(d, &art, &name, size); + if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { + sym.dynamic = dynamic; + } d.set_symbol_registration(&name, reg); d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); - d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); - let threaded = crate::cmd::threads::frames(d); - let id = replace_with_instance(d, &ids, &name, place)?; - // Frames of threaded text in the symbol leave their threads with the text they show. - crate::cmd::threads::leave_threads(d, &threaded); + let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); Ok(id) })?; - Ok( - json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }), - ) + Ok(json!({ + "name": name, + "id": id.0, + "registration": reg.0, + "exportType": export.id(), + "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), + "type": type_id(dynamic), + })) } pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { @@ -188,9 +250,10 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { let export = export_type_param(p, C)?; let reg = registration_param(p, C)?; let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; + let dynamic = type_param(p, C)?; let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); - if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() { - return Err(bad(C, "pass newName, registration, exportType and/or nineSlice")); + if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() { + return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type")); } if let Some(ref n) = new_name && n != &name @@ -218,6 +281,14 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); } + // Symbol editing mode follows the new name, and so does its layer. + if let Some(e) = d.symbol_edit.as_mut().filter(|e| e.symbol == name) { + e.symbol = n.clone(); + let layer = e.layer; + if let Some(l) = d.node_mut(layer) { + l.name = Some(n.clone()); + } + } } if let Some(r) = reg { d.set_symbol_registration(&final_name, r); @@ -228,6 +299,13 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { if let Some(g) = nine { d.set_symbol_nine_slice(&final_name, g); } + if let Some(dynamic) = dynamic + && let Some(sym) = d.symbols.iter_mut().find(|x| x.name == final_name) + { + // A static symbol's instances drop their own appearance changes. + sym.dynamic = dynamic; + fit_overrides(d, &instances_of(d, Some(&final_name))); + } Ok(()) })?; let d = &s.doc()?.doc; @@ -236,6 +314,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { "registration": d.symbol_registration(&final_name).0, "exportType": d.symbol_export_type(&final_name).id(), "nineSlice": nine_slice_json(d, &final_name), + "type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)), })) } @@ -266,11 +345,12 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0 })) } -/// The plain art of instance `inst` in document space (fresh ids). -fn expanded_instance(d: &mut Document, inst: &Node) -> Option { +/// The plain art of instance `inst` in document space (fresh ids), with the instance's own +/// appearance changes to a dynamic symbol's art when `own`. +fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option { let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; let sym = d.symbols.iter().find(|s| &s.name == symbol)?; - let mut art = (*sym.art).clone(); + let mut art = if own { vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst) } else { (*sym.art).clone() }; if let Some(f) = inst.appearance.fill() && let Some(c) = f.paint.color() { @@ -289,11 +369,13 @@ fn expanded_instance(d: &mut Document, inst: &Node) -> Option { Some(art) } -fn break_links(d: &mut Document, ids: &[NodeId]) -> Result> { +/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the +/// art's ids. +fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result> { let mut out = vec![]; for id in ids { let Some(inst) = d.node(*id).cloned() else { continue }; - let Some(art) = expanded_instance(d, &inst) else { continue }; + let Some(art) = expanded_instance(d, &inst, own) else { continue }; let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?; let aid = art.id; d.remove(*id)?; @@ -303,7 +385,7 @@ fn break_links(d: &mut Document, ids: &[NodeId]) -> Result> { Ok(out) } -fn selected_instances(s: &Session, p: &Value) -> Result> { +pub(super) fn selected_instances(s: &Session, p: &Value) -> Result> { let d = &s.doc()?.doc; let mut out = vec![]; for id in roots(s, p)? { @@ -324,86 +406,151 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("no symbol instances selected".into())); } let out = s.edit("Break Link to Symbol", |d, sel| { - let out = break_links(d, &ids)?; + let out = break_links(d, &ids, true)?; sel.set(out.iter().copied()); Ok(out) })?; Ok(json!({ "ids": ids_json(&out) })) } -pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result { - let ids = selected_instances(s, p)?; - let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?; - let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) { - Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(), - _ => return Err(EngineError::Other("select a symbol instance".into())), - }; - let out = s.edit("Edit Symbol", |d, sel| { - let out = break_links(d, &[first])?; - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "name": name, "ids": ids_json(&out) })) -} - pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { const C: &str = "symbol.update"; let name = name_param(p, C)?.to_string(); if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { return Err(bad(C, format!("no symbol named `{name}`"))); } + // Redefining the symbol being edited leaves symbol editing mode in the same step. + let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name); + if session.is_some() { + crate::cmd::settle_interaction(s)?; + s.end_text_edit(); + } let ids = roots(s, p)?; + // The art on the editing layer can't redefine it: the symbol would hold an instance of itself. + if let Some(se) = &session { + let d = &s.doc()?.doc; + if ids.iter().any(|i| d.ancestry(*i).is_some_and(|a| a.contains(&se.layer))) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } + } let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); let (art, size, c) = normalize(art)?; let old = natural_size(&s.doc()?.doc, &name); + let editing = session.is_some(); let id = s.edit("Redefine Symbol", |d, sel| { + if editing { + crate::cmd::symboledit::finish(d, sel); + } let art = d.reid(&art); if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { sym.art = Arc::new(art); } set_natural_size(d, &name, Some(size)); let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1); - for i in instances_of(d, Some(&name)) { - if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) { + let instances = instances_of(d, Some(&name)); + for i in &instances { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*i).map(|n| &mut n.kind) { *xf *= fix; } } + // Each instance keeps its appearance changes to the objects the new art still has. + fit_overrides(d, &instances); let reg = d.symbol_registration(&name); - let threaded = crate::cmd::threads::frames(d); - let id = replace_with_instance(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; - // Frames of threaded text in the symbol leave their threads with the text they show. - crate::cmd::threads::leave_threads(d, &threaded); + let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); Ok(id) })?; + if let Some(se) = &session { + crate::cmd::symboledit::leave_editing(s, se)?; + } Ok(json!({ "name": name, "id": id.0 })) } +/// How many levels of nested instances Delete Symbol expands before it gives up. +const MAX_DELETE_ROUNDS: usize = 256; + pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result { const C: &str = "symbol.delete"; - let name = name_param(p, C)?.to_string(); - if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { + // `names` deletes several symbols in one undo step (the Symbols panel's Select All Unused, #4918). + let names: Vec = match p.get("names") { + Some(v) => { + let a = v.as_array().ok_or_else(|| bad(C, "names must be an array of symbol names"))?; + let mut names = Vec::with_capacity(a.len()); + for n in a { + let n = n.as_str().ok_or_else(|| bad(C, "names must be an array of symbol names"))?; + if !names.iter().any(|x: &String| x == n) { + names.push(n.to_string()); + } + } + if names.is_empty() { + return Err(bad(C, "names is empty")); + } + names + } + None => vec![name_param(p, C)?.to_string()], + }; + let d = &s.doc()?.doc; + if let Some(name) = names.iter().find(|n| !d.symbols.iter().any(|x| &x.name == *n)) { return Err(bad(C, format!("no symbol named `{name}`"))); } let expand = switch_or(p, "expandInstances", true, C)?; - s.edit("Delete Symbol", |d, _| { - let inst = instances_of(d, Some(&name)); - if expand { - break_links(d, &inst)?; - } else { - remove_each(d, &inst)?; + // Deleting the symbol being edited leaves symbol editing mode in the same step. + let session = s.doc()?.doc.symbol_edit.clone().filter(|e| names.contains(&e.symbol)); + let editing = session.is_some(); + if editing { + crate::cmd::settle_interaction(s)?; + s.end_text_edit(); + } + let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" }; + s.edit(label, |d, sel| { + if editing { + crate::cmd::symboledit::finish(d, sel); } - d.symbols.retain(|x| x.name != name); - set_natural_size(d, &name, None); - d.set_symbol_registration(&name, SymbolRegistration::CENTER); - d.clear_symbol_export_type(&name); - d.set_symbol_nine_slice(&name, None); - if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { - d.unknown.remove(CURRENT_SYMBOL); + // Every instance goes before any definition, whatever the order of `names`: expanding an + // instance of one symbol can bring out instances of another being deleted (nested in its + // art), which expand in turn while their definitions are still there. Each round expands + // one level of nesting, so the rounds are capped. + let of_names = |d: &Document| { + let mut v = vec![]; + d.walk(|n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && names.contains(symbol) + { + v.push(n.id); + } + }); + v + }; + for _ in 0..=MAX_DELETE_ROUNDS { + let inst = of_names(d); + if inst.is_empty() { + break; + } + if expand { + break_links(d, &inst, true)?; + } else { + remove_each(d, &inst)?; + } + } + if !of_names(d).is_empty() { + return Err(EngineError::Other("the symbols are nested too deeply to expand their instances".into())); + } + for name in &names { + d.symbols.retain(|x| &x.name != name); + set_natural_size(d, name, None); + d.set_symbol_registration(name, SymbolRegistration::CENTER); + d.clear_symbol_export_type(name); + d.set_symbol_nine_slice(name, None); + if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { + d.unknown.remove(CURRENT_SYMBOL); + } } Ok(()) })?; + if let Some(se) = &session { + crate::cmd::symboledit::leave_editing(s, se)?; + } ok() } @@ -420,7 +567,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { let nine = d.symbol_nine_slice(&name); s.edit("Duplicate Symbol", |d, _| { let art = d.reid(&sym.art); - d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) }); set_natural_size(d, &new, Some(size)); d.set_symbol_registration(&new, reg); d.set_symbol_export_type(&new, export); @@ -443,15 +590,21 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result { s.edit("Replace Symbol", |d, _| { let new = natural_size(d, &name); for id in &ids { - let old = match d.node(*id).map(|n| &n.kind) { - Some(NodeKind::SymbolInstance { symbol, .. }) => natural_size(d, symbol), + let (old, other) = match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => (natural_size(d, symbol), *symbol != name), _ => continue, }; - if let Some(NodeKind::SymbolInstance { symbol, xf }) = d.node_mut(*id).map(|n| &mut n.kind) { + let Some(n) = d.node_mut(*id) else { continue }; + if let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind { *symbol = name.clone(); *xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1); } + // An override's path names an object of the old symbol's art. + if other && !n.extras().symbol_overrides.is_empty() { + n.extras_mut().symbol_overrides.clear(); + } } + fit_overrides(d, &ids); Ok(()) })?; Ok(json!({ "ids": ids_json(&ids) })) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index d6d51e4637..bdfed01752 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -41,7 +41,7 @@ pub use live_paint::live_paint_gaps; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; -pub use trace::{TracePreset, TracePresetChange}; +pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced}; use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view}; /// Name of an Image Trace group. diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index c523c5bf8b..00bcc1c830 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1,4 +1,7 @@ +use std::collections::HashMap; + use vectorcraft_color::Swatch; +use vectorcraft_doc::ImageObject; use super::{ Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point, @@ -219,18 +222,16 @@ fn trace_params(s: &Session, c: &str, p: &Value) -> Result { Ok(params) } -/// Document swatch `w`'s solid color with the paint a trace fills with it: a global or spot color, -/// or a tint of one, linked to its swatch as `swatch_solid` (paint.rs) links it; any other color -/// unlinked. The color is the one the paint shows (a Lab spot color's CMYK equivalent when the Spot -/// Colors options use CMYK values). +/// Document swatch `w`'s displayed solid color and unlinked trace paint. A tint uses its tinted +/// color; a Lab spot color uses its CMYK equivalent when the Spot Colors options use CMYK values. fn trace_swatch_paint(d: &Document, w: &Swatch) -> Option<(Color, Paint)> { let linked = d.swatch_link(&w.name).and_then(|(base, tint)| d.tint_paint(&base, tint)); let color = linked.as_ref().and_then(Paint::color).or_else(|| w.paint.color())?; - Some((color, linked.unwrap_or_else(|| Paint::solid(color)))) + Some((color, Paint::solid(color))) } /// Document Library with `colorGroup`: the solid colors of the active document's color group -/// `name` (so named exactly, else ignoring case), each with its paint ([`trace_swatch_paint`]). +/// `name` (so named exactly, else ignoring case), each with its unlinked paint ([`trace_swatch_paint`]). /// Errors name command `c`. ([`trace_params`] has checked that the library is the document's /// swatches.) fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result> { @@ -246,9 +247,7 @@ fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result Result> { if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary { return Ok(vec![]); @@ -369,8 +368,34 @@ fn grouped(d: &mut Document, nodes: Vec, parents: &[Option]) -> Vec roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect() } -pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { - let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; +/// What a trace depends on: the object traced (an image, or an Image Trace object traced again), +/// its image, and the settings it is traced with. The tracer makes the same paths of the same +/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own. +#[derive(Clone, Debug, PartialEq)] +struct TraceInputs { + target: NodeId, + image: Box, + /// The settings traced with, as JSON. + params: Value, + /// Document Library: the library's colours, which the JSON leaves out + /// ([`tr::TraceParams::swatches`]). + swatches: Vec<[u8; 3]>, +} + +/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace. +struct Prepared { + inputs: TraceInputs, + trace: tr::TraceParams, + view: Option, + /// The settings asked for, which the Image Trace object keeps. + params_json: Value, + preset_label: String, + library: Vec<([u8; 3], Paint)>, + bytes: Arc>, +} + +/// What command `c` with params `p` traces, and how, from the session: everything but the trace. +fn prepare(s: &Session, c: &str, p: &Value) -> Result { let mut params = trace_params(s, c, p)?; let view = view_param(c, p)?; let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; @@ -384,15 +409,9 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result named.to_string(), None => "Custom".to_string(), }; - // A saved preset's settings join the journal entry, so a replay traces as this run did after - // the preset is changed, renamed or deleted. - if let Some(q) = s.trace_preset(named).filter(|_| tr::preset(named).is_none()) { - let recorded = serde_json::to_value(&q.params).map_err(|e| EngineError::Other(e.to_string()))?; - s.note_journal("savedPreset", recorded); - } let roots = root_ids(s, p)?; // The image (inside a trace group, or selected directly). - let (target, img) = { + let (target, image) = { let d = &s.doc()?.doc; roots .iter() @@ -409,20 +428,139 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result bool + Sync)) -> Result { + // An image over the tracer's size is traced scaled down (the paths are scaled back). + let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?; + if !steps(0, 0) { + return Err(EngineError::Cancelled); + } + let res = tr::trace_watched(&raster, params, MAX_TRACE_ANCHORS, steps).map_err(|e| match e { + tr::TraceError::Cancelled => EngineError::Cancelled, + e => EngineError::Other(e.to_string()), + })?; + Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res }) +} + +/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] +/// takes what `imageTrace.make` or `imageTrace.makeAndExpand` traces from the session, checked as +/// the command checks it; [`TraceRun::run`] decodes and traces the image without the session, on +/// any thread; [`Traced::hand_in`] gives the result to the command. +pub struct TraceRun { + command: &'static str, + params: Value, + prepared: Prepared, +} + +impl TraceRun { + /// The trace `command` (`imageTrace.make` or `imageTrace.makeAndExpand`) with params `p` makes + /// in the active document. + pub fn prepare(s: &Session, command: &str, p: &Value) -> Result { + let command = match command { + "imageTrace.make" => "imageTrace.make", + "imageTrace.makeAndExpand" => "imageTrace.makeAndExpand", + other => return Err(EngineError::Other(format!("`{other}` doesn't trace an image"))), + }; + let prepared = prepare(s, command, p)?; + // The object traced is named, so the command applies the trace to it whatever is + // selected by then. + let mut params = if p.is_object() { p.clone() } else { json!({}) }; + if let Some(o) = params.as_object_mut() { + o.remove("ids"); + o.insert("id".into(), json!(prepared.inputs.target.0)); + } + Ok(TraceRun { command, params, prepared }) + } + + /// `imageTrace.make` or `imageTrace.makeAndExpand`. + pub fn command(&self) -> &'static str { + self.command + } + + /// The command's params that apply this trace: those it was prepared with, the object traced + /// in `id`. + pub fn params(&self) -> &Value { + &self.params + } + + /// The object it traces: an image, or an Image Trace object traced again. + pub fn target(&self) -> NodeId { + self.prepared.inputs.target + } + + /// The size in pixels of the image it traces. + pub fn image_size(&self) -> (u32, u32) { + (self.prepared.inputs.image.width, self.prepared.inputs.image.height) + } + + /// Does it still apply: would the command trace the same object, image and settings now? + pub fn current(&self, s: &Session) -> bool { + prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) + } + + /// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it + /// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no + /// document, so it can run on any thread. + pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { + trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps) + } +} + +pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { + let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?; + // A saved preset's settings join the journal entry, so a replay traces as this run did after + // the preset is changed, renamed or deleted. + let named = str_param(p, "preset").unwrap_or("Default"); + if let Some(q) = s.trace_preset(named).filter(|_| tr::preset(named).is_none()) { + let recorded = serde_json::to_value(&q.params).map_err(|e| EngineError::Other(e.to_string()))?; + s.note_journal("savedPreset", recorded); + } + // A trace handed in for these very inputs ([`TraceRun`]), else one made now. + let Traced { raster, res, .. } = match s.trace_hand_off.take() { + Some(traced) if traced.inputs == inputs => traced, + _ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?, + }; + let TraceInputs { target, image: img, .. } = inputs; + let warnings = trace_warnings((img.width, img.height), raster, res.worked_at); // Pixel space of the decoded raster → the image object's pixel space → document. - let sx = img.width.max(1) as f64 / raster.width.max(1) as f64; - let sy = img.height.max(1) as f64 / raster.height.max(1) as f64; + let sx = img.width.max(1) as f64 / raster.0.max(1) as f64; + let sy = img.height.max(1) as f64 / raster.1.max(1) as f64; let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy); // Document units per raster pixel (stroke widths). let unit = xf.determinant().abs().sqrt(); let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len()); let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" }; + // A library color fills with the swatch's displayed color (its model kept), unlinked. + // Keep the first swatch that traces as a given color. Build the lookup once per trace. + let mut by_color: HashMap<[u8; 3], &Paint> = HashMap::new(); + for (rgb, paint) in &library { + by_color.entry(*rgb).or_insert(paint); + } let id = s.edit(label, |d, sel| { let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; let mut image = if is_trace_group(&src) { @@ -450,12 +588,8 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Vec { "Invert Colors", ["Edit", "Edit Colors"], None, - "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step → {changed}", + "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step → {changed}", has_selection, |s, p| recolor(s, p, "Invert Colors", &invert) ), @@ -178,10 +178,10 @@ impl Scope { /// One recolouring pass, the colour visitor Edit Colors and Recolor Artwork share: `f` maps the /// solid colours and gradient stops of fills, strokes and text runs, gradient-mesh points, the -/// pixels of embedded images and the art of patterns used as fills or strokes. A recoloured image -/// becomes a new image and a recoloured pattern a new pattern swatch ("Dots 2"); the originals stay -/// as they are for other objects. Colours that change lose their swatch link. Only nodes that -/// change are kept as copies. +/// pixels of embedded images without a colorize paint and the art of patterns used as fills or +/// strokes. A recoloured image becomes a new image and a recoloured pattern a new pattern swatch +/// ("Dots 2"); the originals stay as they are for other objects. Colours that change lose their +/// swatch link. Only nodes that change are kept as copies. pub(crate) struct Recolor<'a> { f: &'a dyn Fn(Color) -> Color, /// Maps solid colours and gradient stops with their link and tint in place of `f`. @@ -335,13 +335,24 @@ pub(crate) fn recolor(s: &mut Session, p: &Value, label: &str, f: &dyn Fn(Color) run_pass(s, p, label, Recolor::new(Scope::of(p), f)) } +/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch +/// link and tint. +pub(crate) fn recolor_links(s: &mut Session, p: &Value, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result { + run_pass(s, p, label, Recolor::with_links(Scope::of(p), f, links)) +} + /// Run `pass` on the `ids` param's objects (default: the selection) as one undo step. fn run_pass(s: &mut Session, p: &Value, label: &str, pass: Recolor) -> Result { let ids = match ids_param(p, "ids") { Some(v) => v, None => selected_roots(s)?, }; - let n = s.edit(label, |d, _| Ok(pass.run(d, &ids)))?; + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); + let n = s.edit(label, |d, _| { + let n = pass.run(d, &ids); + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(label, e))?; + Ok(n) + })?; Ok(json!({ "changed": n })) } @@ -451,6 +462,7 @@ fn filled_leaves(d: &Document, roots: &[NodeId]) -> Vec { fn fill_color(n: &Node) -> Option { match &n.kind { NodeKind::Text(t) => t.first_style().fill.color(), + NodeKind::Image(_) => n.extras().colorize.as_deref().and_then(Paint::color).or_else(|| n.appearance.fill_paint().color()), NodeKind::Mesh(m) => { let k = m.points.len() as f32; let sum = m.points.iter().map(|p| p.color.to_rgb()).reduce(|a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]])?; @@ -487,6 +499,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result { BlendOrder::Vertical => "Blend Vertically", }; let fills = Scope { fill: true, stroke: false, images: false, patterns: false }; + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); let changed = s.edit(label, |d, _| { let mut changed = 0; for (i, id) in ids.iter().enumerate().take(n - 1).skip(1) { @@ -504,6 +517,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result { }; changed += Recolor::new(fills, &*f).run(d, &[*id]); } + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(label, e))?; Ok(changed) })?; Ok(json!({ "changed": changed })) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index b1ad12800e..0cf1a0ec7e 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -645,6 +645,7 @@ fn set_spot(s: &mut Session, p: &Value) -> Result { } if sw.spot != spot { let n = name.clone(); + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); s.edit("Swatch Options", |d, _| { if let Some(w) = d.swatch_mut(&n) { w.spot = spot; @@ -652,7 +653,7 @@ fn set_spot(s: &mut Session, p: &Value) -> Result { w.global = true; } } - Ok(()) + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e)) })?; } Ok(json!({"name": name, "spot": spot})) diff --git a/crates/engine/src/cmd/compoundshape.rs b/crates/engine/src/cmd/compoundshape.rs new file mode 100644 index 0000000000..7c5aa3f5bb --- /dev/null +++ b/crates/engine/src/cmd/compoundshape.rs @@ -0,0 +1,256 @@ +//! Pathfinder panel › compound shapes (`object.compoundShape.*`): Make Compound Shape (what +//! Alt-clicking a Shape Mode button does), a member's shape mode, Release and Expand Compound +//! Shape. A compound shape is a group marked so ([`Node::is_compound_shape`]) whose members each +//! have a [`ShapeMode`]; `vectorcraft-effects` draws it as the area they make +//! ([`effects::compound_shape_area`]). + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode}; +use vectorcraft_render::effects; + +use super::edit::{roots_of, selected_roots}; +use super::pathops::{pf_leaves, shape_node, style_of}; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi}; + +const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "object.compoundShape.make", + "Make Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}", + has_multi, + make + ), + cmd!( + "object.compoundShape.setMode", + "Shape Mode", + ["Window", "Pathfinder"], + None, + "{mode: \"add\"|\"subtract\"|\"intersect\"|\"exclude\", ids?: [id…] (selected first; default: the selection)} the members of compound shapes that the selected objects are or are in take the shape mode (what clicking a Shape Mode button does with members selected); the backmost member's mode doesn't change the shape → {ids}", + has_member, + set_mode + ), + cmd!( + "object.compoundShape.release", + "Release Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become their members again, as they were before Make Compound Shape, selected → {ids}", + has_compound_shape, + release + ), + cmd!( + "object.compoundShape.expand", + "Expand Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become the path, or compound path, of the area they draw, painted as they are, selected → {ids}", + has_compound_shape, + expand + ), + ] +} + +/// The innermost compound shape holding `id` (not `id` itself), with the member of it that `id` is +/// or is in. +fn holder(d: &Document, id: NodeId) -> Option<(NodeId, NodeId)> { + let up = d.ancestry(id)?; + up.windows(2).rev().find_map(|w| match w { + [shape, member] if d.node(*shape).is_some_and(Node::is_compound_shape) => Some((*shape, *member)), + _ => None, + }) +} + +/// The compound shape `id` is or is in (the innermost). +fn shape_of(d: &Document, id: NodeId) -> Option { + if d.node(id)?.is_compound_shape() { Some(id) } else { holder(d, id).map(|(shape, _)| shape) } +} + +/// The compound shapes the selection is or is in, outermost only, in paint order. +fn selected_shapes(s: &Session) -> Result> { + let st = s.doc()?; + let mut shapes: Vec = vec![]; + for id in st.selection.in_paint_order(&st.doc) { + if let Some(shape) = shape_of(&st.doc, id).filter(|shape| !shapes.contains(shape)) { + shapes.push(shape); + } + } + Ok(roots_of(&st.doc, shapes)) +} + +/// The members of compound shapes that the selected objects are or are in. +fn selected_members(s: &Session) -> Result> { + let st = s.doc()?; + let mut members: Vec = vec![]; + for id in &st.selection.objects { + if let Some((_, member)) = holder(&st.doc, *id).filter(|(_, m)| !members.contains(m)) { + members.push(member); + } + } + Ok(members) +} + +/// The shape modes of the compound-shape members the selection is or is in (none when it is in +/// none): the Pathfinder panel lights the Shape Mode button they share. +pub fn selected_member_modes(s: &Session) -> Vec { + let Some(st) = s.active() else { return vec![] }; + let members = selected_members(s).unwrap_or_default(); + members.iter().filter_map(|id| st.doc.node(*id)).map(|n| n.extras().shape_mode).collect() +} + +/// The selection is or is in a compound shape. +fn has_compound_shape(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| shape_of(&st.doc, *id).is_some()) { Ok(()) } else { Err("select a compound shape".into()) } +} + +/// The selection is or is in a member of a compound shape. +fn has_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| holder(&st.doc, *id).is_some()) { Ok(()) } else { Err("select members of a compound shape".into()) } +} + +/// The `mode` param: one of [`MODE_NAMES`], or `default` when it is missing (`None`: required). +fn mode_param(p: &Value, cmd: &str, default: Option) -> Result { + match super::object::choice(p, cmd, "mode", &MODE_NAMES)? { + Some(name) => ShapeMode::parse(name), + None => default, + } + .ok_or_else(|| bad(cmd, format!("`mode` must be one of {}", MODE_NAMES.join(", ")))) +} + +fn ids_json(ids: &[NodeId]) -> Value { + json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) +} + +fn make(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.compoundShape.make"; + let mode = mode_param(p, C, Some(ShapeMode::Add))?; + let roots = selected_roots(s)?; + if roots.len() < 2 { + return Err(bad(C, "select at least two objects")); + } + let d = &s.doc()?.doc; + let mut members = Vec::with_capacity(roots.len()); + for id in &roots { + let n = d.node(*id).ok_or(EngineError::NoNode(*id))?; + if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Text(_)) { + return Err(bad(C, "compound shapes take paths, compound paths, groups, compound shapes and type")); + } + members.push(n); + } + // The paint and transparency of the topmost member in Add, Intersect or Exclude mode: as they + // all have `mode`, the topmost, or the backmost when they all subtract. + let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() }; + let style = order.into_iter().find_map(|n| { + let mut lv = vec![]; + pf_leaves(n, &mut lv); + lv.last().map(style_of) + }); + let id = s.edit("Make Compound Shape", |d, sel| { + let gid = d.alloc_id(); + let id = d.wrap(&roots, |children| { + let children = children + .into_iter() + .map(|c| { + let mut c = Arc::unwrap_or_clone(c); + c.extras_mut().shape_mode = mode; + Arc::new(c) + }) + .collect(); + let mut g = Node::group(gid, children); + g.extras_mut().compound_shape = true; + if let Some(style) = &style { + style.apply(&mut g); + } + g + })?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + +fn set_mode(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.compoundShape.setMode"; + let mode = mode_param(p, C, None)?; + let members = selected_members(s)?; + if members.is_empty() { + return Err(bad(C, "select members of a compound shape")); + } + // Members already in the mode leave the document and its undo history as they are. + let d = &s.doc()?.doc; + if members.iter().all(|id| d.node(*id).is_some_and(|n| n.extras().shape_mode == mode)) { + return Ok(ids_json(&members)); + } + s.edit("Shape Mode", |d, _| { + for id in &members { + d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().shape_mode = mode; + } + Ok(()) + })?; + Ok(ids_json(&members)) +} + +fn release(s: &mut Session, _: &Value) -> Result { + let shapes = selected_shapes(s)?; + if shapes.is_empty() { + return Err(bad("object.compoundShape.release", "select a compound shape")); + } + let ids = s.edit("Release Compound Shape", |d, sel| { + let (mut items, mut released) = (vec![], vec![]); + for id in &shapes { + let members = d.node(*id).and_then(Node::children).ok_or(EngineError::NoNode(*id))?; + let out: Vec = members + .iter() + .map(|c| { + let mut c = (**c).clone(); + c.extras_mut().shape_mode = ShapeMode::Add; + released.push(c.id); + c + }) + .collect(); + items.push((*id, out)); + } + d.insert_beside(items, true)?; + sel.set(released.iter().copied()); + Ok(released) + })?; + Ok(ids_json(&ids)) +} + +fn expand(s: &mut Session, _: &Value) -> Result { + const LABEL: &str = "Expand Compound Shape"; + let shapes = selected_shapes(s)?; + if shapes.is_empty() { + return Err(bad("object.compoundShape.expand", "select a compound shape")); + } + let ids = s.edit(LABEL, |d, sel| { + let (mut items, mut made) = (vec![], vec![]); + for id in &shapes { + let shape = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?; + let area = effects::compound_shape_area(&shape, effects::text_outliner()) + .ok_or_else(|| EngineError::Other("the compound shape is too complex to expand".into()))?; + if area.is_empty() { + return Err(EngineError::Other(format!("{LABEL} produced an empty result"))); + } + let mut n = shape_node(d, area, None); + let mut appearance = (*shape.appearance).clone(); + appearance.contents_index = None; + n.appearance = appearance.into(); + (n.opacity, n.blend, n.name) = (shape.opacity, shape.blend, shape.name.clone()); + made.push(n.id); + items.push((*id, vec![n])); + } + d.insert_beside(items, true)?; + sel.set(made.iter().copied()); + Ok(made) + })?; + Ok(ids_json(&ids)) +} diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index a943ee10dd..65a6ee0c37 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -739,7 +739,17 @@ fn text_create(s: &mut Session, p: &Value) -> Result { let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); - Ok(super::typecmd::with_overflow(s, id.as_slice(), made)) + let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); + if p.get("font").is_some() || p.get("style").is_some() { + let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.runs.iter().map(|r| super::fonts::font_of(&r.style)).collect(), + _ => Default::default(), + }; + if let Some(w) = super::fonts::set_font_warning(runs) { + made["warning"] = json!(w); + } + } + Ok(made) } /// The paragraph attributes new type gets (the Type tools, `text.create`): aligned to the start of @@ -801,7 +811,8 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result CharStyle { let mut style = CharStyle::default(); if let Some(sz) = p.get("size").and_then(Value::as_f64) { @@ -821,5 +832,7 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(), None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), }; + // In the document's language (Document Setup), none for the default. + style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string); style } diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 3da43957c8..7a0643ca51 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Move in Perspective", [], None, - "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid)} slide objects within their plane (unattached objects attach to `plane`/the active plane first); snapping lands the nearer edge of the objects' joint bounds on a gridline within a quarter cell; Transform Again repeats it", + "{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: bool (default false; constrain each in-plane move to its plane's nearest axis or 45° diagonal)} slide objects within their own planes (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the first plane's joint bounds toward a gridline within a quarter cell while preserving the constrained direction; Transform Again repeats it", has_doc, persp_move ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 8481770274..eda17fee88 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -52,8 +52,8 @@ pub(super) fn grid_set(s: &mut Session, p: &Value) -> Result { old.adopt_stored_attachments(d); for (id, plane, depth) in persp::attached_roots(d) { let h = old.homography_at(plane, depth).and_then(|h| h.inverse()).zip(g.homography_at(plane, depth)); - let (hi, h) = h.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?; - let m = h.then_after(&hi); + let m = h.and_then(|(hi, h)| h.checked_then_after(&hi)); + let m = m.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?; warp_checked(d, id, &m)?; } } @@ -98,17 +98,15 @@ pub(super) fn roots(s: &Session, p: &Value) -> Result> { } } -/// Map `n` with `f`, failing if any point would leave the plane's visible side. /// Map `n` with `h` (type and symbols in perspective keep their art and are drawn through it), -/// failing if any point would leave the plane's visible side. +/// failing if any point would leave the plane's visible side or a projection would not be finite. fn warp_checked(d: &mut Document, id: NodeId, h: &Homography) -> Result<()> { let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; let mut pts = vec![]; collect_points(n, &mut pts); - if pts.iter().any(|q| h.apply(*q).is_none()) { + if pts.iter().any(|q| h.apply(*q).is_none()) || !project_node(n, h) { return Err(EngineError::Other("the object would cross the horizon of the perspective plane".into())); } - project_node(n, h); Ok(()) } @@ -284,12 +282,42 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { } let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok(); let (perp, copy) = (switch_or(p, "perpendicular", false, C)?, switch_or(p, "copy", false, C)?); + let constrain = switch_or(p, "constrain", false, C)?; // `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false. check_switches(p, &["snap"], C)?; // Snap to Grid: a correction for the objects on the first one's plane and depth. - let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) }; - let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| { - dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| f.2) + let snap_to = if constrain && !perp { + let doc = &s.doc()?.doc; + let g = grid_of(doc); + g.plane_bounds(doc, &ids) + .and_then(|(plane, depth, _)| { + let h = g.homography_at(plane, depth)?; + let start = h.inverse()?.apply(from)?; + let delta = g.plane_delta(plane, depth, from, to)?; + h.apply(start + vectorcraft_tools::distort::perspective::constrain_move_delta(delta).1) + }) + .unwrap_or(to) + } else { + to + }; + let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, snap_to)) }; + let snapped = move |pl: Plane, depth: f64, raw: vectorcraft_geom::Vec2| { + let (direction, dv) = + if constrain { vectorcraft_tools::distort::perspective::constrain_move_delta(raw) } else { (vectorcraft_geom::Vec2::ZERO, raw) }; + dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| { + if !constrain { + return f.2; + } + if direction.x.abs() < 1e-12 { + return vectorcraft_geom::Vec2::new(0.0, f.2.y); + } + if direction.y.abs() < 1e-12 { + return vectorcraft_geom::Vec2::new(f.2.x, 0.0); + } + let (correction, axis) = + if f.2.x == 0.0 || (f.2.y != 0.0 && f.2.y.abs() < f.2.x.abs()) { (f.2.y, direction.y) } else { (f.2.x, direction.x) }; + direction * (correction / axis) + }) }; // In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches. let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> { @@ -569,11 +597,14 @@ pub(super) fn edit_text(s: &mut Session, p: &Value) -> Result { let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("select type in perspective".into())) }; // Shown flat where it is drawn: the type moves there and the projection moves the other // way, so the picture stays. - let (Some(flat), Some(drawn)) = (t.bounds(), t.bounds().and_then(|b| h.map_rect_bbox(b))) else { return Ok(()) }; + let Some(flat) = t.bounds() else { return Ok(()) }; + let cross = || EngineError::Other("the object would cross the horizon of the perspective plane".into()); + let drawn = h.map_rect_bbox(flat).ok_or_else(cross)?; let shift = vectorcraft_geom::Affine::translate(drawn.center() - flat.center()); + let moved = h.checked_then_after(&Homography::from_affine(shift.inverse())).ok_or_else(cross)?; t.transform(shift); if let Some(rec) = n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) { - rec.projection = Some(h.then_after(&Homography::from_affine(shift.inverse())).to_array()); + rec.projection = Some(moved.to_array()); rec.editing = true; } Ok(()) diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index 3f7b632250..f5cb1d6b72 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -127,8 +127,8 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value "discardWhiteOverprint" => s.discard_white_overprint = flag(k, v)?, "language" => { let l = v.as_str().unwrap_or(""); - let (name, quotes) = LANGUAGES.iter().find(|(n, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| { - bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _)| *n).collect::>().join(", "))) + let (name, _, quotes) = LANGUAGES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| { + bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::>().join(", "))) })?; s.language = name.to_string(); s.quotes = *quotes; diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 57066e3b9c..6946463e3e 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…], size?: pt (10), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", has_doc, erase_region ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…], size?: pt (10), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index b8c598a2d6..760105dcfb 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -1,7 +1,8 @@ use super::{ Appearance, Arc, Beside, Cap, Color, Document, EngineError, FillRule, Join, Node, NodeId, NodeKind, Paint, PathData, Point, PressureProfile, - Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, po, + Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, number_or, po, }; +use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile}; // ---------- helpers ---------- @@ -64,6 +65,36 @@ pub(super) fn stroke_pressure(samples: &[(Point, Option)]) -> Option 1e-9 { s / at } else { 0.0 }, p))) } +/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with +/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for +/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size. +pub(super) fn size_pressure(p: &Value, samples: &[(Point, Option)], cmd: &str) -> Result> { + match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { + None | Some(Ok("fixed")) => Ok(None), + Some(Ok("pressure")) => { + let variation = number_or(p, "sizeVariation", 0.0, cmd)?; + if !(variation.is_finite() && variation >= 0.0) { + return Err(bad(cmd, "sizeVariation must be 0 or more")); + } + Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))) + } + Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))), + Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))), + } +} + +/// The area a stroke along `spine` covers with Size set to Pressure: as wide at each point as +/// [`vectorcraft_tools::draw2::pressure_size`] gives for the pressure `prof` records there, with +/// round ends and joins, its overlaps united into one outline. +pub(super) fn pressure_region(spine: &PathData, size: f64, variation: f64, prof: &PressureProfile) -> Result { + let widest = size + variation; + let width = |t: f64| vectorcraft_tools::draw2::pressure_size(size, variation, prof.at(t)) / widest; + let profile = WidthProfile { points: prof.points.iter().map(|&(t, _)| (t, width(t), width(t))).collect() }; + let round = StrokeLayer { cap: LineCap::Round, join: LineJoin::Round, ..StrokeLayer::new(Paint::None, widest) }; + let outline = PathData::from_bezpath(&vectorcraft_render::width_outline(&spine.to_bezpath(), widest, &profile, &round, 0.05)); + po::try_unite_all(&[(&outline, FillRule::NonZero)]).map_err(|e| EngineError::Other(e.to_string())) +} + /// The length of a subpath. pub(super) fn subpath_len(sp: &SubPath) -> f64 { use kurbo::ParamCurveArclen; diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index e3a566f170..d9be52764e 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,6 +1,6 @@ use super::common::{ - dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, replace_with_pieces, sibling_with, target_paths, - usize_opt, + dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, samples_param, + sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath, @@ -264,30 +264,47 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseRegion"; - let pts = points_param(p, "points", C)?; + let samples = samples_param(p, "points", C)?; let size = number_or(p, "size", 10.0, C)?; if !(size.is_finite() && size > 0.0) { return Err(bad(C, "size must be positive")); } let angle = number_or(p, "angle", 0.0, C)?; let roundness = number_or(p, "roundness", 100.0, C)?; + let pressure = size_pressure(p, &samples, C)?; + let pts: Vec = samples.into_iter().map(|(pt, _)| pt).collect(); let r = size / 2.0; - // The tip's short axis: an open path is sampled at least every half of it. - let short = size * roundness.clamp(1.0, 100.0) / 100.0; + // The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it. + let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0)); + let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0; let st = s.doc()?; - let region = eraser_area(&pts, size, angle, roundness); // A point is under the tip when, with the tip squashed back into a circle, it is within the // circle's radius of the squashed drag. - let squash = eraser_tip(angle, roundness).inverse(); + let stretch = eraser_tip(angle, roundness); + let squash = stretch.inverse(); let round: Vec = pts.iter().map(|q| squash * *q).collect(); + // With Size set to Pressure the tip is as wide as the pen pressed: the area is the squashed + // drag outlined at those widths, stretched back, and a point is under it when the area holds it. + let pressed = match (&pressure, round.len() > 1) { + (Some((prof, v)), true) => Some(pressure_region(&PathData::single(SubPath::polyline(&round, false)), size, *v, prof)?.transformed(stretch)), + (Some((prof, v)), false) => Some(eraser_area(&pts, vectorcraft_tools::draw2::pressure_size(size, *v, prof.at(0.0)), angle, roundness)), + (None, _) => None, + }; + let reach = pressure.as_ref().map_or(r, |(_, v)| (size + v) / 2.0); + let region = pressed.clone().unwrap_or_else(|| eraser_area(&pts, size, angle, roundness)); + let outline = pressed.map(|pd| pd.to_bezpath()); + let under = |q: Point| match &outline { + Some(bp) => fill_contains(bp, FillRule::NonZero, q), + None => dist_to_polyline(&round, squash * q) <= r, + }; let mut plan: Vec<(NodeId, Vec)> = vec![]; - for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, r))? { + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? { if pd.is_closed() { if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { continue; } plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); - } else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| dist_to_polyline(&round, squash * q) <= r) { + } else if let Some(pieces) = erase_outline(&pd, short / 2.0, &under) { plan.push((id, pieces)); } } diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index e037f0cc1e..95a2cd94bb 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -1,6 +1,6 @@ use super::common::{ - brush_region, path_kind, path_mut, path_of, points_param, poly_bounds, samples_param, stroke_paint, stroke_pressure, subpath_len, target_paths, - within_input_bound, + brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint, stroke_pressure, + subpath_len, target_paths, within_input_bound, }; use super::{ Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point, @@ -45,7 +45,10 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { if sp.anchors.len() < 3 { return sp; } - let fitted = po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false }); + let fitted = po::simplify_with( + &PathData::single(sp.clone()), + &SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false, ..Default::default() }, + ); fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp) } @@ -368,11 +371,29 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec pub(super) fn blob(s: &mut Session, p: &Value) -> Result { const C: &str = "path.blob"; - let pts = points_param(p, "points", C)?; + let samples = samples_param(p, "points", C)?; let size = number_or(p, "size", 10.0, C)?; if !(size.is_finite() && size > 0.0) { return Err(bad(C, "size must be positive")); } + let angle = number_or(p, "angle", 0.0, C)?; + let roundness = number_or(p, "roundness", 100.0, C)?; + if !angle.is_finite() || !roundness.is_finite() { + return Err(bad(C, "angle and roundness must be finite")); + } + let angle = angle.clamp(-180.0, 180.0); + let roundness = roundness.clamp(0.0, 100.0); + let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness); + let squash = tip.inverse(); + // Width profiles use distance along the spine, so measure pressure on the same squashed + // points that the outline reads for a non-round tip. + let mapped_samples: Vec<(Point, Option)> = + if roundness < 100.0 { samples.iter().map(|(pt, pressure)| (squash * *pt, *pressure)).collect() } else { samples.clone() }; + let pressure = size_pressure(p, &mapped_samples, C)?; + let pts: Vec = samples.into_iter().map(|(pt, _)| pt).collect(); + let mapped_pts: Vec = mapped_samples.into_iter().map(|(pt, _)| pt).collect(); + // The widest the brush gets: the area merges look in. + let reach = pressure.as_ref().map_or(size, |(_, v)| size + v); // With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil // stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to // its start), the brush follows every point. @@ -380,11 +401,35 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)), }; - let fitted = fidelity - .filter(|_| pts.len() > 1) - .map(|tol| po::outline_stroke(&PathData::single(fit_freehand(&pts, tol, false)), size, Cap::Round, Join::Round, 4.0)) - .filter(|r| !r.is_empty()); - let region = fitted.unwrap_or_else(|| brush_region(&pts, size)); + let spine = |tol: Option| { + let path = match tol { + Some(tol) => PathData::single(fit_freehand(&pts, tol, false)), + None => PathData::single(SubPath::polyline(&pts, false)), + }; + if roundness < 100.0 { path.transformed(squash) } else { path } + }; + let region = match (&pressure, pts.len() > 1) { + (Some((prof, variation)), true) => { + let fitted = match fidelity { + Some(tol) => Some(pressure_region(&spine(Some(tol)), size, *variation, prof)?).filter(|r| !r.is_empty()), + None => None, + }; + match fitted { + Some(r) => r, + None => pressure_region(&spine(None), size, *variation, prof)?, + } + } + // A click: one dab as wide as the pen pressed. + (Some((prof, variation)), false) => brush_region(&mapped_pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))), + (None, _) => { + let fitted = fidelity + .filter(|_| pts.len() > 1) + .map(|tol| po::outline_stroke(&spine(Some(tol)), size, Cap::Round, Join::Round, 4.0)) + .filter(|r| !r.is_empty()); + fitted.unwrap_or_else(|| brush_region(&mapped_pts, size)) + } + }; + let region = if roundness < 100.0 { region.transformed(tip) } else { region }; if region.is_empty() { return Err(EngineError::Other("empty brush stroke".into())); } @@ -404,7 +449,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { let all = Selection::default(); let from = if only_selection { &st.selection } else { &all }; // A fitted stroke can curve outside the points' bounds, so the area also takes in the shape. - let area = region.control_bounds().map_or_else(|| poly_bounds(&pts, size), |b| b.union(poly_bounds(&pts, size))); + let area = region.control_bounds().map_or_else(|| poly_bounds(&pts, reach), |b| b.union(poly_bounds(&pts, reach))); for id in target_paths(&st.doc, from, area) { let Some(n) = st.doc.node(id) else { continue }; if !blob_match(n, &paint) { diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index fd783aa4f7..a4aa1f79a8 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -9,7 +9,7 @@ use super::{ /// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles. fn refit_run(anchors: &[Anchor], tol: f64) -> Vec { let piece = PathData::single(SubPath::new(anchors.to_vec(), false)); - let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false }); + let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }); let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() }; let (f, l) = (anchors[0], anchors[anchors.len() - 1]); let last = out.len() - 1; @@ -32,8 +32,10 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio if sp.closed { let Some(k) = marked.iter().position(|m| !m) else { // Everything is in range: smooth the whole closed path. - let f = - po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false }); + let f = po::simplify_with( + &PathData::single(sp.clone()), + &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() }, + ); return f.subpaths.into_iter().next(); }; // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a2cab84a89..62a17bda3b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -481,6 +481,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let label = e.label.clone(); let costs = e.costs(); let editing = st.doc.mask_edit.map(|m| m.layer); + let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.redo.last()); @@ -494,6 +495,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { crate::deselect_hidden(&menu, &st.doc, &mut st.selection); st.sync_new_art(); super::maskedit::follow_history(st, editing); + super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); Ok(json!({ "undone": label })) @@ -507,6 +509,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let label = e.label.clone(); let costs = e.costs(); let editing = st.doc.mask_edit.map(|m| m.layer); + let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.undo.last()); @@ -519,6 +522,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { crate::deselect_hidden(&menu, &st.doc, &mut st.selection); st.sync_new_art(); super::maskedit::follow_history(st, editing); + super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); Ok(json!({ "redone": label })) @@ -566,17 +570,29 @@ pub(crate) fn selected_roots(s: &Session) -> Result> { /// rest still go to the compound path, which holds the paint. pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), true)) + Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true)) +} + +/// [`selected_roots`] for the selected objects inside the isolated object `root` +/// ([`super::inside_isolation`]): `root` itself and objects outside it are left out before the +/// objects held by another selected object are dropped. A selected path of a compound path stands +/// for its compound unless the compound is `root` or `members` is set (as in +/// [`selected_roots_to_transform`]). +pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result> { + let st = s.doc()?; + let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); + Ok(roots_within(&st.doc, ids, |compound| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their /// compound, and ids whose ancestor is also listed, and layers, are dropped. pub(crate) fn roots_of(doc: &Document, ids: Vec) -> Vec { - roots_within(doc, ids, false) + roots_within(doc, ids, |_| false) } -/// [`roots_of`]; with `members`, a compound path's member listed stays itself. -fn roots_within(doc: &Document, ids: Vec, members: bool) -> Vec { +/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the +/// compound's id. +fn roots_within(doc: &Document, ids: Vec, members: impl Fn(NodeId) -> bool) -> Vec { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); // A compound-path member acts as its compound (compounds are one object). @@ -586,7 +602,7 @@ fn roots_within(doc: &Document, ids: Vec, members: bool) -> Vec let path = paths.get(&id); let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty()); match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) { - Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members => (n.id, Some(up.to_vec())), + Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())), _ => (id, path.cloned()), } }) @@ -797,11 +813,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho && (st.doc.paste_remembers_layers || boards.is_some()) && parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer)); // Front/back: relative to the selection (top-most / bottom-most selected object); with - // nothing selected, the top / bottom of the current layer. + // nothing selected, the top / bottom of the current layer. Art other than paths goes beside + // the compound path that holds the selected object, not into it. let anchor = if front || back { let order = st.selection.in_paint_order(&st.doc); let a = if front { order.last() } else { order.first() }; - a.and_then(|id| st.doc.position(*id)) + let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })); + a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id)) } else { None }; @@ -844,17 +862,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))), _ => None, }; + // In a clip group or a clipping layer the bottom child is the clipping path: art pasted + // in back goes above it, not below it. + let floor = |d: &Document, par: Option| usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); let (par, idx) = match (into, anchor, layer) { // Inside the object Draw Inside draws into, on top of what is in it already. (Some(group), ..) => (Some(group), usize::MAX), // Next to the anchor, unless the object goes back to another layer. (None, Some((par, i, _)), l) if l.is_none() || l == par => { let k = placed.get(&par).copied().unwrap_or(0); - (par, if front { i + 1 + k } else { i + k }) + (par, if front { i + 1 + k } else { i.max(floor(d, par)) + k }) } (None, _, l) => { let par = l.or(parent); - (par, if back { placed.get(&par).copied().unwrap_or(0) } else { usize::MAX }) + (par, if back { floor(d, par) + placed.get(&par).copied().unwrap_or(0) } else { usize::MAX }) } }; *placed.entry(par).or_default() += 1; @@ -884,6 +905,15 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho })) } +/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only +/// paths (a compound path holds paths only). +fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId { + match doc.parent_of(id) { + Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p, + _ => id, + } +} + /// The first unlocked layer or sublayer called `name` (topmost first), or a new top layer. fn layer_named(d: &mut Document, name: &str) -> NodeId { let mut found = None; diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index d7c584d9dd..feee6913fb 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -69,7 +69,7 @@ pub fn specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. Hidden fills, strokes and effects are dropped. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. Hidden fills, strokes and effects are dropped. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", can_expand, expand_appearance ), @@ -108,7 +108,7 @@ fn ids_json(ids: &[NodeId]) -> Value { pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result, usize)>> { let roots = appearance_targets(s, p)?; let d = &s.doc()?.doc; - let per = item.per_target(d, &roots); + let per = item.per_target(s, &roots); let shared = if aligned(p) { shared_stack(d, &roots) } else { None }; let mut out = Vec::with_capacity(roots.len()); for (k, (id, item)) in roots.iter().zip(per).enumerate() { @@ -213,15 +213,15 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } } - let mut index = 0; let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", 0, |fx, _| { fx.push(effect.clone()); - index = fx.len() - 1; true })?; - // The item the effect landed on in the first object (the active item applies where it fits). - let first = ids.first().and_then(|id| s.doc().ok()?.doc.node(*id)); + // The item the effect landed on in the object whose row the item is (the first selected object + // for the active item, which applies where it fits), and the effect's index in that object. + let first = ids.get(item.anchor(s, &ids)).and_then(|id| s.doc().ok()?.doc.node(*id)); let landed = first.and_then(|n| item.effects_item(&n.appearance, C).ok().flatten()); + let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1)); Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed })) } @@ -646,6 +646,17 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br out.extend(expanded.into_iter().map(|(id, at)| (id, at + 1))); return Some(m); } + // Vector Halftone: the object becomes its dots, a group (with `id`) of paths with ids of their own. + if let Some(mut m) = vectorcraft_render::addons::halftone::art(d, &n) { + let mut seen = std::collections::HashSet::from([id]); + for c in m.children_mut().into_iter().flatten() { + effects::fresh_ids(d, Arc::make_mut(c), &mut seen); + } + if !listed_n { + out.push((id, 0)); + } + return Some(m); + } let image = raster_image(d, &n); let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); @@ -670,10 +681,12 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br // Type, images, symbol instances, live objects (and paths whose Transform effect copies // them with a gradient or changes their fills and strokes): through their outlines. let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), + NodeKind::SymbolInstance { symbol, .. } => { + d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, &n)) + } _ => None, }; - effects::expand_outlined(Some(&*d), &v, symbol.as_deref()).map(|mut m| { + effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| { expand_pieces(d, &mut m, true, brushes, &mut stroke_art); m }) @@ -721,6 +734,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br fn expand_appearance(s: &mut Session, p: &Value) -> Result { let roots = appearance_targets(s, p)?; let failed = vectorcraft_render::decode_failures(); + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); let ids = s.edit("Expand Appearance", |d, _| { let brushes = vectorcraft_brush::library(d); let mut out = vec![]; @@ -734,6 +748,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { if out.is_empty() { return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into())); } + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?; Ok(out) })?; let mut out = json!({ "ids": ids_json(&ids) }); diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index c23c578d06..d85b3358c7 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -68,7 +68,7 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() { assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"bevel": "nope"}, "ids": [id.0], "item": null})).is_err()); let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); - assert!(svg.matches("= 2, "{effect}: exported as vector faces"); + assert!(vectorcraft_testkit::svg_shapes(&svg) >= 2, "{effect}: exported as vector faces"); s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); assert!(matches!(node(&s, id).kind, NodeKind::Group { .. }), "{effect}"); assert!(!effects::has_solid(&node(&s, id))); @@ -77,12 +77,35 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(node(&s, id).appearance.effects.len(), 0, "{effect}: back to the plain rectangle"); } - // Type has no outline to extrude. +} + +/// #4715: type extrudes as its glyph outlines, painted with its characters' colour, and stays +/// type: editing its text reshapes the solid. +#[test] +fn type_extrudes_as_its_glyphs_and_stays_editable() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); - let t = s.execute("text.create", &json!({"x": 50, "y": 50, "text": "3D"})).unwrap(); - let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [t["id"]], "item": null})).unwrap_err(); - assert!(err.to_string().contains("requires a path"), "{err}"); + let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": "3D", "size": 72})).unwrap(); + let id = NodeId(t["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#cc2200"})).unwrap(); + s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap(); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::Text(_)), "still type"); + let art = effects::solid_art(&n).expect("a solid of the glyphs"); + let mut faces = 0; + let mut tinted = false; + art.walk(&mut |c| { + if c.path_data().is_some() { + faces += 1; + // Shaded from the characters' red: red stays the strongest channel. + if let Some([r, g, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) { + tinted |= r > g && r > b; + } + } + }); + assert!(faces > 2 && tinted, "{faces} faces, tinted {tinted}"); + s.execute("text.setText", &json!({"ids": [id.0], "text": "3DD"})).unwrap(); + assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "the solid follows the edited text"); } /// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 8dc49b0890..4745437d40 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -189,6 +189,15 @@ fn pattern_fill<'a, 'd>(d: &'d Document, i: &'a AppearanceItem) -> Option<(&'a F } fn expand(s: &mut Session, p: &Value) -> Result { + let scope = s.begin_undo_scope(); + let result = expand_steps(s, p); + if let Some(scope) = scope { + s.end_undo_scope(scope, result.is_err()); + } + result +} + +fn expand_steps(s: &mut Session, p: &Value) -> Result { let object = bool_or(p, "object", true); let fill = bool_or(p, "fill", true); let stroke = bool_or(p, "stroke", true); @@ -218,7 +227,13 @@ fn expand(s: &mut Session, p: &Value) -> Result { s.edit("Expand", |d, _| super::patterncmds::expand_repeats(d, &roots).map(|_| ()))?; } if object && e.effects { - let _ = run_raw(s, "effect.expandAppearance", &json!({})); + // Effects that Expand Appearance can't expand are left as they are. When it refuses to + // leave a process color on a grayscale image with transparency, Expand fails as a whole. + if let Err(e) = run_raw(s, "effect.expandAppearance", &json!({})) + && super::paint::is_colorize_refusal(&e) + { + return Err(e); + } // What is left to expand is in the baked art: Expand Appearance leaves strokes strokes // (#3089), a group's own as stroked paths among its members, which Stroke outlines below. e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?); @@ -429,28 +444,209 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { }) } -/// Expand the pattern fills under `root` that paint a transparent image into the tiles they paint +/// Expand the pattern fills under `root` that paint a transparent or colorized image into the tiles they paint /// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other -/// pattern fills stay. A tile image counts as -/// transparent when its key is in `see_through` (it has see-through pixels), or when it, a group +/// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through +/// pixels), when it has a colorize paint that `colorize` counts, or when it, a group /// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending -/// mode. Returns how many shapes changed. -pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet) -> Result { - let (_, n) = replace_leaves(d, root, |d, l| { - // Most leaves have no pattern fill: skip the ancestry walk for them. - if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { - return None; +/// mode. Blends, envelopes, repeats and Intertwine groups that hold such a fill are expanded +/// first ([`expand_live_with_transparent_image_patterns`]). Hidden shapes and shapes in hidden +/// groups or layers and in template layers stay as they are. A pattern fill in tile art counts +/// too, down to the [`PATTERN_LEVELS`] the canvas draws, and the tile art the expansion makes is +/// expanded again for it. A pattern fill stays, and a live object stays live, when its art would +/// take the expanded art past [`MAX_GENERATED`](vectorcraft_doc::live::MAX_GENERATED) objects. +/// Returns how many objects changed. +pub(crate) fn expand_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, +) -> Result { + expand_transparent_image_patterns_within(d, root, see_through, colorize, vectorcraft_doc::live::MAX_GENERATED) +} + +/// [`expand_transparent_image_patterns`] with the expanded art held to `budget` objects. +pub(crate) fn expand_transparent_image_patterns_within( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + budget: usize, +) -> Result { + let mut changed = 0; + let made = std::cell::Cell::new(0usize); + // Each pass brings the patterns in the expanded tiles' art up one level. + for levels in (1..=PATTERN_LEVELS).rev() { + let live = expand_live_with_transparent_image_patterns(d, root, see_through, colorize, levels, &made, budget)?; + let (_, n) = replace_leaves(d, root, |d, l| { + // Past the budget, and for most leaves, which have no pattern fill, skip the ancestry walk. + if made.get() >= budget || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + return None; + } + // The expanded art would be shown. + if !d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).all(drawn) { + return None; + } + let which = |d: &Document, i: &AppearanceItem| transparent_pattern_fill(d, l, i, see_through, colorize, levels); + let art = expand_patterns_where(d, l, which, budget - made.get())?; + // The copies of the shape's other items count too. + let count = art.count_with_masks(); + if count > budget - made.get() { + return None; + } + made.set(made.get() + count); + Some(art) + })?; + if live + n == 0 { + break; } - let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); - let transparent = |d: &Document, i: &AppearanceItem| { - pattern_fill(d, i).is_some_and(|(f, def, _)| { - let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; - def.art.iter().any(|a| transparent_image(a, see_through, on)) - }) - }; - expand_patterns_where(d, l, transparent) - })?; - Ok(n) + changed += live + n; + } + Ok(changed) +} + +/// How many levels of patterns the canvas draws: a pattern fill in the art of a pattern, and so +/// on, as [`vectorcraft_render`] draws them. +const PATTERN_LEVELS: u32 = 3; + +/// Whether a layer of `d` holds a pattern fill that [`expand_transparent_image_patterns`] would +/// expand with `see_through` and `colorize` ([`holds_transparent_image_patterns`]). +pub(crate) fn has_transparent_image_patterns(d: &Document, see_through: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool) -> bool { + d.layers.iter().any(|l| holds_transparent_image_patterns(d, l, see_through, colorize, PATTERN_LEVELS)) +} + +/// Whether `n`, art of `d`, is or holds a shown path or compound path (in groups, blends, +/// envelopes, repeats and Intertwine groups) with a pattern fill that +/// [`transparent_pattern_fill`] counts with `levels`. Guides, clipping paths and template layers +/// don't count. +fn holds_transparent_image_patterns( + d: &Document, + n: &Node, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, +) -> bool { + if !drawn(n) { + return false; + } + match &n.kind { + NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false, + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| transparent_pattern_fill(d, n, i, see_through, colorize, levels)) + } + _ => n.children().is_some_and(|ch| ch.iter().any(|c| holds_transparent_image_patterns(d, c, see_through, colorize, levels))), + } +} + +/// Whether `n` is shown and isn't a template layer. +fn drawn(n: &Node) -> bool { + n.visible && !matches!(n.kind, NodeKind::Layer { template: true, .. }) +} + +/// Expand the shown blends, envelopes, repeats and Intertwine groups under `root` that hold a +/// pattern fill [`holds_transparent_image_patterns`] counts with `levels` into the art the exporters write for +/// them ([`expand_live_deep`](vectorcraft_render::effects::expand_live_deep), under one budget for +/// everything nested in each), so the shapes they draw are leaves. The objects that art holds count +/// in `made`, and an object whose art would take `made` past `budget` stays live. Returns how many +/// were expanded. +fn expand_live_with_transparent_image_patterns( + d: &mut Document, + root: NodeId, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, + made: &std::cell::Cell, + budget: usize, +) -> Result { + fn outermost( + d: &Document, + n: &Node, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, + out: &mut Vec, + ) { + if !drawn(n) { + return; + } + match &n.kind { + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { + if holds_transparent_image_patterns(d, n, see_through, colorize, levels) { + out.push(n.id); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + children.iter().for_each(|c| outermost(d, c, see_through, colorize, levels, out)); + } + _ => {} + } + } + /// Fresh ids for everything under `n`: copies of the same art share theirs. + fn fresh_ids(d: &mut Document, n: &mut Node) { + for c in n.children_mut().into_iter().flatten() { + let c = Arc::make_mut(c); + c.id = d.alloc_id(); + fresh_ids(d, c); + } + } + let mut live = vec![]; + if let Some(n) = d.node(root) { + outermost(d, n, see_through, colorize, levels, &mut live); + } + let mut count = 0; + for id in &live { + if made.get() >= budget { + break; + } + let Some(n) = d.node(*id) else { continue }; + // Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]), + // and leave the object live when that can't be done. + let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue }; + // An object whose art would take the expanded art past the budget stays live. + let size = g.count_with_masks(); + if size > budget - made.get() { + continue; + } + made.set(made.get() + size); + g.id = *id; + fresh_ids(d, &mut g); + *d.node_mut(*id).ok_or(EngineError::NoNode(*id))? = g; + count += 1; + } + Ok(count) +} + +/// Whether `i`, an item of leaf `l`, is a pattern fill whose tile art holds a transparent image +/// ([`transparent_image`], through pattern fills in that art down to `levels` patterns), +/// counting the fill's and the shape's opacity and blending mode. +fn transparent_pattern_fill( + d: &Document, + l: &Node, + i: &AppearanceItem, + see_through: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + levels: u32, +) -> bool { + let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); + pattern_fill_holds_transparent_image(d, i, see_through, colorize, shape, levels) +} + +/// Whether `i` is a pattern fill whose tile art holds a transparent image ([`transparent_image`]), +/// down to `levels` patterns, counting the fill's opacity and blending mode, or anything when `on`. +fn pattern_fill_holds_transparent_image( + d: &Document, + i: &AppearanceItem, + keys: &BTreeSet, + colorize: &dyn Fn(&Document, &Node) -> bool, + on: bool, + levels: u32, +) -> bool { + if levels == 0 { + return false; + } + let Some((f, def, _)) = pattern_fill(d, i) else { return false }; + let on = on || f.opacity < 1.0 || f.blend != BlendMode::Normal; + def.art.iter().any(|a| transparent_image(d, a, keys, colorize, on, levels - 1)) } /// Whether `n` has opacity or a blending mode of its own. @@ -458,13 +654,21 @@ fn blended(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal } -/// Whether `n` is or holds a transparent image: one with see-through pixels (key in `keys`), or -/// with opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`. -fn transparent_image(n: &Node, keys: &BTreeSet, on: bool) -> bool { +/// Whether `n` (art of `d`) is or holds an image with see-through pixels (key in `keys`), a +/// colorize paint that `colorize` counts, opacity or a blending mode of its own or of a group in +/// `n`, or anywhere when `on`, also in the tile art of the pattern fills of the paths in `n`, down +/// to `levels` patterns. Hidden art doesn't count. +fn transparent_image(d: &Document, n: &Node, keys: &BTreeSet, colorize: &dyn Fn(&Document, &Node) -> bool, on: bool, levels: u32) -> bool { + if !n.visible { + return false; + } let on = on || blended(n); match &n.kind { - NodeKind::Image(im) => on || keys.contains(&im.key), - _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))), + NodeKind::Image(im) => on || keys.contains(&im.key) || (n.extras().colorize.is_some() && colorize(d, n)), + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + n.appearance.items.iter().any(|i| pattern_fill_holds_transparent_image(d, i, keys, colorize, on, levels)) + } + _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(d, c, keys, colorize, on, levels))), } } @@ -476,12 +680,12 @@ fn transparent_image(n: &Node, keys: &BTreeSet, on: bool) -> bool { /// ([`pattern_tiles`]). A pattern fill that lays no tile there stays. `None` when no pattern fill /// lays a tile. fn expand_patterns(d: &mut Document, l: &Node) -> Option { - expand_patterns_where(d, l, |_, _| true) + expand_patterns_where(d, l, |_, _| true, usize::MAX) } /// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other -/// items. -fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool) -> Option { +/// items, as does a pattern fill whose tiles would take the tiles of `l` past `budget` objects. +fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool, budget: usize) -> Option { if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i)) { @@ -494,19 +698,47 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & let mut parts = vec![]; let mut rest = vec![]; let mut expanded = false; + // What `assemble` adds around the tiles when every picked fill expands: a copy of the path for + // each run of other items, a group around the parts and one for the path's transparency, and + // the path's opacity mask. + let (mut copies, mut run, mut picked) = (0usize, false, vec![]); + for i in &l.appearance.items { + if let Some((f, _, _)) = pattern_fill(d, i).filter(|_| which(d, i)) { + run = false; + picked.push(f.opacity < 1.0 || f.blend != BlendMode::Normal); + } else if i.visible() && !i.paint().is_none() && !run { + (copies, run) = (copies + 1, true); + } + } + let group = copies + picked.len() > 1 || !l.appearance.effects.is_empty(); + // A lone tile group with transparency of its own goes in a group for the path's. + let transparency = blended(l) && !group && picked.first().is_some_and(|b| *b); + let around = copies.saturating_mul(l.count()) + usize::from(group) + usize::from(transparency) + l.count_with_masks().saturating_sub(l.count()); + let mut left = budget.saturating_sub(around); + // A fill that expands while others follow leaves room for the copy and group that those take + // if they don't fit, and once one doesn't fit, the ones after it stay too. + let (mut later, mut full) = (picked.len(), false); for item in &l.appearance.items { let fill = pattern_fill(d, item).filter(|_| which(d, item)).map(|(f, def, xf)| (f, def.clone(), xf)); - let tiles = fill.and_then(|(f, def, xf)| { + later -= usize::from(fill.is_some()); + let room = if later > 0 { left.saturating_sub(l.count() + 1) } else { left }; + let tiles = fill.filter(|_| !full).and_then(|(f, def, xf)| { let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?; - let t = pattern_tiles(d, &def, xf, bounds); + let Some(t) = pattern_tiles(d, &def, xf, bounds, room) else { + full = true; + return None; + }; (!t.is_empty()).then_some((f, fl, t)) }); - let Some(art) = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)) else { + let art = tiles.and_then(|(f, fl, t)| tile_art(d, &fl, f, &t)); + full |= art.as_ref().is_some_and(|a| a.count_with_masks() > room); + let Some(art) = art.filter(|a| a.count_with_masks() <= room) else { if item.visible() && !item.paint().is_none() { rest.push(item.clone()); } continue; }; + left -= art.count_with_masks(); if !rest.is_empty() { parts.push(styled_copy(d, l, std::mem::take(&mut rest))); } @@ -533,30 +765,38 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, & /// not, and when it does more than move art that holds a symbol instance, whose strokes the canvas /// draws scaled with the tile and an instance does not scale. Random Transform effects and brushes /// that vary at random in the art are baked first ([`seeds_baked`], [`random_brushes_baked`]). -fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect) -> Vec { +/// `None` when the tiles would hold more than `budget` objects. +fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect, budget: usize) -> Option> { if !moves_only(xf) && def.art.iter().any(|a| has_instances(a)) { - return vec![]; + return Some(vec![]); } let Some(def) = seeds_baked(def) else { - return vec![]; + return Some(vec![]); }; let brushes = vectorcraft_brush::library(d); let def = random_brushes_baked(d, &brushes, def); let def = &*def; + let per_tile = def.art.iter().map(|a| a.count_with_masks()).sum::(); + if def.offsets_covering(xf.inverse().transform_rect_bbox(bounds)).len().saturating_mul(per_tile) > budget { + return None; + } let scaling = Scaling { strokes: true, effects: Some(vectorcraft_render::effects::scale_effect), patterns: true, ..Scaling::default() }; if scales_evenly(xf) && (moves_only(xf) || !def.art.iter().any(|a| has_geometry_effects(a))) { - return def.instances_in_with(xf, bounds, scaling); + return Some(def.instances_in_with(xf, bounds, scaling)); } if def.art.iter().any(|a| has_unbakeable_effects(a)) { - return vec![]; + return Some(vec![]); } let placed = Scaling { patterns: true, ..Scaling::default() }; let mut tiles = def.instances_in_with(Affine::IDENTITY, xf.inverse().transform_rect_bbox(bounds), placed); + // Outlined strokes and effects can make more objects than the art had. + let mut left = budget; for t in &mut tiles { *t = prepared(d, &brushes, t); + left = left.checked_sub(t.count_with_masks())?; place_art(t, xf, scaling); } - tiles + Some(tiles) } /// Pattern `def` with each path in its art (opacity masks included) that has a random Transform diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6893c6f845..fb9419052e 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -33,9 +33,11 @@ pub(crate) mod imagemap; mod legacy_ai; mod load; pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; +mod jp2read; mod metafile; mod naming; mod native; +mod pcxread; pub mod pdf; mod pdfimport; pub mod pngtext; @@ -55,6 +57,7 @@ pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings}; pub(crate) use encode::{anti_alias, background, with_single_artboard}; pub use export::export_source; +pub(crate) use export::with_artboard_fills; pub(crate) use export::{export_crop, isolated}; pub(crate) use load::check_not_lossy_overwrite; use load::err; @@ -73,6 +76,7 @@ pub(crate) use native::preview_png; pub use native::with_compression_pref; pub use pdfimport::{LoadOptions, page_document}; pub(crate) use save::job_for; +pub(crate) use save::save as save_document; pub use save::{ SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder, @@ -117,11 +121,12 @@ use access::{may_read, may_write}; pub use commands::specs; pub use export_names::artboard_file_names; pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return}; -use export_names::{distinct_names, write_encoded}; +use export_names::{distinct_names_by, write_encoded}; use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable}; pub use formats::{ - DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, file_stem, - format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, writable_format, + DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, + file_stem, format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, + writable_format, }; #[cfg(test)] @@ -129,6 +134,8 @@ mod tests; #[cfg(test)] mod tests_affinity; #[cfg(test)] +mod tests_artboard_fill; +#[cfg(test)] mod tests_pdf; #[cfg(test)] mod tests_pdfcolor; @@ -192,6 +199,11 @@ mod tests_psd; #[cfg(test)] mod tests_psdread; +#[cfg(test)] +mod tests_jp2read; +#[cfg(test)] +mod tests_pcxread; + #[cfg(test)] mod tests_epsimport; diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index d1db603025..e11b6adcd6 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -34,6 +34,7 @@ struct Run<'a> { override_export: bool, destination: &'a str, dest_folder: Option<&'a str>, + dataset_file_naming: &'a str, } /// Play `commands` on each source file or data set. @@ -90,6 +91,7 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { override_export: bool_or(p, "overrideExport", true), destination, dest_folder: dest_folder.as_deref(), + dataset_file_naming: p.get("datasetFileNaming").map_or("fileDataSetName", |v| v.as_str().unwrap_or("")), }; match source { "folder" => batch_folder(s, C, p, override_open, &run), @@ -135,9 +137,6 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: #[cfg(not(target_arch = "wasm32"))] fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { - use super::distinct_names; - use super::screens::file_part; - let st = s.doc()?; let names: Vec = st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect(); if names.is_empty() { @@ -147,11 +146,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets"))); } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); - // Data set files are named File + Data Set Name (helpx, for Override Save/Export; the folder - // destination uses the same name). `file_part` writes the characters Windows does not allow in a - // file name (`/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters) in the data set's - // name as `-`, and `distinct_names` adds `-2`, `-3`… to a name an earlier data set used. - let stems = distinct_names(names.iter().map(|name| format!("{doc_stem}_{}", file_part(name)))); + let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; let steps = filter_steps(run.steps, true, false); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); @@ -227,7 +222,7 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou "folder" => { let folder = run.dest_folder.ok_or_else(|| bad("action.batch", "missing destination folder"))?; let out_ext = if ext.is_empty() { "vectorcraft" } else { ext }; - let out = std::path::Path::new(folder).join(format!("{stem}.{out_ext}")); + let out = output_path(folder, stem, out_ext).ok_or_else(|| bad("action.batch", "unsafe destination file name"))?; let out = out.to_string_lossy().into_owned(); // When `close` is false (data sets), write a copy so the template keeps its path. write_result(s, &out, out_ext, !close)?; @@ -240,6 +235,174 @@ fn finish_destination(s: &mut Session, run: &Run<'_>, stem: &str, ext: &str, sou } } +/// Builds the three data set naming forms, replaces unsafe name characters, and adds `-2`, `-3` +/// suffixes when a stem was used earlier or its output already exists in a folder the batch may +/// read and write. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Result> { + use super::screens::{file_part, safe_file_name}; + + if !matches!(naming, "fileNumber" | "fileDataSetName" | "dataSetName") { + return Err(bad("action.batch", "`datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName`")); + } + let doc_stem = safe_file_name(doc_stem); + let doc_stem = if doc_stem.is_empty() || matches!(doc_stem.as_str(), "." | "..") { "Untitled" } else { &doc_stem }; + let bases = names.iter().enumerate().map(|(i, name)| { + let safe = file_part(name); + let safe_data_set = safe_file_name(&safe); + let ordinal = format!("{doc_stem}{:03}", i + 1); + match naming { + "fileNumber" => ordinal, + "dataSetName" if !safe_data_set.is_empty() => safe_data_set, + "dataSetName" => ordinal, + _ => format!("{doc_stem}_{safe}"), + } + }); + let outputs = dataset_output_extensions(run, doc); + let mut taken = std::collections::HashSet::new(); + let mut reserved = std::collections::HashSet::new(); + let mut stems = Vec::with_capacity(bases.len()); + for base in bases { + let mut candidate = base.clone(); + let mut suffix = 2; + while taken.contains(&candidate.to_lowercase()) + || dataset_output_paths(run.dest_folder, &candidate, &outputs, doc) + .iter() + .any(|path| reserved.contains(&path.to_string_lossy().to_lowercase())) + || dataset_output_exists(run.dest_folder, &candidate, &outputs, doc) + { + if suffix > 10_000 { + return Err(bad("action.batch", "no free data set file name in destination folder")); + } + candidate = format!("{base}-{suffix}"); + suffix += 1; + } + taken.insert(candidate.to_lowercase()); + reserved + .extend(dataset_output_paths(run.dest_folder, &candidate, &outputs, doc).into_iter().map(|path| path.to_string_lossy().to_lowercase())); + stems.push(candidate); + } + Ok(stems) +} + +#[cfg(not(target_arch = "wasm32"))] +struct DatasetOutput { + ext: String, + artboards: bool, + joiner: &'static str, +} + +/// Lists step output extensions and reserves artboard file names for saves with any artboard or +/// exports with multiple artboards. Per-artboard names count for vectorcraft, template, AI and AIT +/// saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec { + let mut outputs = Vec::new(); + if run.destination == "folder" { + outputs.push(DatasetOutput { ext: "vectorcraft".into(), artboards: false, joiner: "-" }); + } + for step in run.steps { + let id = step.get("command").and_then(Value::as_str).unwrap_or(""); + let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + || (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection")); + if writes { + let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); + let ext = match format { + Some(format) if super::format(format).is_some() => format_extension(format), + Some(_) => continue, + None => "vectorcraft".to_string(), + }; + if safe_extension(&ext) { + let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft"); + let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let artboards = if is_save { + !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") + } else { + doc.artboards.len() > 1 + && id == "document.export" + && matches!( + format_id, + "svg" + | "svgz" + | "eps" + | "png" + | "jpg" + | "webp" + | "gif" + | "png8" + | "tiff" + | "bmp" + | "tga" + | "psd" + | "dxf" + | "emf" + | "wmf" + | "ai" + ) + }; + outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } }); + } + } + } + outputs +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_exists(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> bool { + let Some(folder) = folder else { return false }; + if super::may_read(folder).is_err() || super::may_write(folder).is_err() { + return false; + } + dataset_output_paths(Some(folder), stem, outputs, doc).iter().any(|path| { + let path_text = path.to_string_lossy(); + super::may_read(&path_text).is_ok() && super::may_write(&path_text).is_ok() && path.exists() + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn dataset_output_paths(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> Vec { + let Some(folder) = folder else { return Vec::new() }; + let boards: Vec<_> = (0..doc.artboards.len()).collect(); + let mut parts = super::artboard_file_names(doc, &boards); + for board in boards { + parts.extend(super::artboard_file_names(doc, &[board])); + } + let mut paths = Vec::new(); + for output in outputs { + if !safe_extension(&output.ext) || super::format(&output.ext).is_none() { + continue; + } + paths.extend(output_path(folder, stem, &output.ext)); + if output.artboards { + for part in &parts { + paths.extend(output_path(folder, &format!("{stem}{}{part}", output.joiner), &output.ext)); + } + } + } + paths +} + +/// Returns whether an extension is safe to use in an output file name. +#[cfg(not(target_arch = "wasm32"))] +fn safe_extension(ext: &str) -> bool { + !ext.is_empty() && !ext.contains(['/', '\\', ':']) && !ext.contains("..") +} + +/// Returns a path inside the destination folder for a safe stem and extension. +#[cfg(not(target_arch = "wasm32"))] +fn output_path(folder: &str, stem: &str, ext: &str) -> Option { + use std::path::Path; + if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(std::path::is_separator) || !safe_extension(ext) { + return None; + } + let name = format!("{stem}.{ext}"); + if name.contains(std::path::is_separator) { + return None; + } + let path = Path::new(folder).join(name); + (path.parent() == Some(Path::new(folder))).then_some(path) +} + /// Save when the extension is a Save format; otherwise export (PNG, JPEG…). /// `as_copy`: `file.saveCopy` so the open document keeps its path (data-set batches). #[cfg(not(target_arch = "wasm32"))] @@ -285,7 +448,10 @@ fn rewrite_paths( Some(f) => format_extension(f), None => default_ext.to_string(), }; - let file = std::path::Path::new(folder).join(format!("{stem}.{ext}")); + if params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()).is_some_and(|f| super::format(f).is_none()) { + return c; + } + let Some(file) = output_path(folder, stem, &ext) else { return c }; params.insert("path".into(), json!(file.to_string_lossy())); if let Some(o) = c.as_object_mut() { o.insert("params".into(), Value::Object(params)); @@ -411,6 +577,74 @@ mod tests { assert!(dest.join("b.svg").is_file(), "b.svg written"); } + #[cfg(unix)] + #[test] + fn batch_folder_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-src"); + let dest = tmp("backslash-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "object.unlockAll", "params": {}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert!(dest.join("a\\b.svg").is_file(), "{r}"); + } + + #[cfg(unix)] + #[test] + fn batch_folder_override_export_keeps_backslash_in_source_file_name() { + let src = tmp("backslash-export-src"); + let dest = tmp("backslash-export-dest"); + write_svg(&src, "a\\b.svg", "#f00"); + let mut s = Session::new(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "folder", + "folder": src.to_string_lossy(), + "destination": "folder", + "destinationFolder": dest.to_string_lossy(), + "stopOnError": true, + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["count"], 1, "{r}"); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(r["stopped"], false, "{r}"); + assert_eq!(file_names(&dest), ["a\\b.svg"], "{r}"); + } + + #[test] + fn output_path_accepts_only_platform_file_name_separators() { + let folder = tmp("output-path"); + let folder = folder.to_string_lossy(); + let backslash = output_path(&folder, "a\\b", "svg"); + #[cfg(windows)] + assert!(backslash.is_none()); + #[cfg(not(windows))] + assert_eq!(backslash, Some(std::path::Path::new(folder.as_ref()).join("a\\b.svg"))); + for stem in ["a/b", ".", "..", ""] { + assert!(output_path(&folder, stem, "svg").is_none(), "{stem:?}"); + } + #[cfg(windows)] + assert_eq!(std::path::Path::new("a\\b.svg").file_stem(), Some(std::ffi::OsStr::new("b"))); + } + #[test] fn batch_skips_open_steps_when_override_open() { let src = tmp("open"); @@ -548,6 +782,412 @@ mod tests { s } + fn named_batch(s: &mut Session, dest: &std::path::Path, naming: Option<&str>) -> Value { + let mut p = json!({ + "source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "object.unlockAll", "params": {}}] + }); + if let Some(naming) = naming { + p["datasetFileNaming"] = json!(naming); + } + s.execute("action.batch", &p).unwrap() + } + + #[test] + fn batch_data_set_naming_choices_and_omitted_default() { + for (i, (naming, want)) in [ + (Some("fileNumber"), ["source001.vectorcraft", "source002.vectorcraft"]), + (Some("fileDataSetName"), ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + (Some("dataSetName"), ["Alpha.vectorcraft", "Beta.vectorcraft"]), + (None, ["source_Alpha.vectorcraft", "source_Beta.vectorcraft"]), + ] + .into_iter() + .enumerate() + { + let dest = tmp(&format!("choice-{i}")); + let mut s = with_data_sets(&["Alpha", "Beta"]); + let saved = tmp(&format!("saved-{i}")).join("source.vectorcraft"); + s.execute("document.save", &json!({"path": saved.to_string_lossy()})).unwrap(); + let r = named_batch(&mut s, &dest, naming); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), want, "{naming:?}: {r}"); + } + } + + #[test] + fn batch_file_number_uses_three_digits_through_500() { + let names: Vec = (1..=500).map(|n| format!("Set {n}")).collect(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + dataset_file_naming: "fileDataSetName", + }; + let stems = dataset_stems(&names, "source", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(); + for n in [1, 2, 10, 100, 500] { + assert_eq!(stems[n - 1], format!("source{n:03}")); + } + } + + #[test] + fn batch_unsaved_data_set_names_and_empty_fallback() { + let dest = tmp("unsaved-number"); + let mut s = with_data_sets(&["Alpha"]); + assert_eq!(named_batch(&mut s, &dest, Some("fileNumber"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled001.vectorcraft"]); + let dest = tmp("unsaved-name"); + assert_eq!(named_batch(&mut s, &dest, Some("fileDataSetName"))["failed"], 0); + assert_eq!(file_names(&dest), ["Untitled_Alpha.vectorcraft"]); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: None, + dataset_file_naming: "fileDataSetName", + }; + assert_eq!(dataset_stems(&[String::new()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); + assert_eq!(dataset_stems(&[" ".to_string()], "Untitled", "dataSetName", &run, &s.doc().unwrap().doc).unwrap(), ["Untitled001"]); + } + + #[test] + fn batch_data_set_name_collisions_and_existing_files() { + let clear = tmp("choice-collision-clear"); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &clear, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&clear), ["a-b-2.vectorcraft", "a-b.vectorcraft"]); + let dest = tmp("choice-collision"); + std::fs::write(dest.join("a-b.vectorcraft"), b"keep").unwrap(); + let mut s = with_data_sets(&["a:b", "a-b"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("a-b.vectorcraft")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["a-b-2.vectorcraft", "a-b-3.vectorcraft", "a-b.vectorcraft"]); + } + + #[test] + fn batch_data_set_name_avoids_windows_device_files() { + let dest = tmp("choice-device"); + let mut s = with_data_sets(&["CON"]); + let r = named_batch(&mut s, &dest, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&dest), ["CON-.vectorcraft"]); + } + + #[test] + fn batch_override_export_keeps_existing_output() { + let dest = tmp("choice-existing-export"); + std::fs::write(dest.join("Alpha.svg"), b"keep").unwrap(); + let mut s = with_data_sets(&["Alpha"]); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "svg"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(dest.join("Alpha.svg")).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2.svg", "Alpha.svg"]); + } + + #[test] + fn batch_artboard_export_keeps_existing_output() { + let dest = tmp("choice-existing-artboard-export"); + let existing = dest.join("Alpha-Artboard-1.png"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "png", "useArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.png", "Alpha-2-Artboard-2.png", "Alpha-Artboard-1.png"]); + } + + #[test] + fn batch_remembered_separate_artboards_keeps_existing_output() { + let source = tmp("choice-remembered-separate-source"); + let dest = tmp("choice-remembered-separate-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": source.join("source.vectorcraft").to_string_lossy(), "separateArtboards": true})).unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save"}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!( + file_names(&dest), + ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2-Artboard-2.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft",] + ); + } + + #[test] + fn batch_single_artboard_save_keeps_existing_artboard_file() { + let source = tmp("choice-single-artboard-source"); + let dest = tmp("choice-single-artboard-dest"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 1})).unwrap(); + s.execute( + "document.save", + &json!({ + "path": source.join("source.vectorcraft").to_string_lossy(), + "separateArtboards": true + }), + ) + .unwrap(); + assert!(source.join("source-Artboard-1.vectorcraft").exists()); + + let existing = dest.join("Alpha-Artboard-1.vectorcraft"); + std::fs::write(&existing, b"keep").unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-2-Artboard-1.vectorcraft", "Alpha-2.vectorcraft", "Alpha-Artboard-1.vectorcraft"]); + } + + #[test] + fn batch_pdf_export_ignores_artboard_named_file() { + let dest = tmp("choice-pdf-artboard-name"); + let existing = dest.join("Alpha-Artboard-1.pdf"); + std::fs::write(&existing, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.export", "params": {"format": "pdf"}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(existing).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.pdf", "Alpha.pdf"]); + } + + #[test] + fn batch_separate_artboards_ignores_unrelated_extension() { + let dest = tmp("choice-separate-unrelated-extension"); + let unrelated = dest.join("Alpha-photo.png"); + std::fs::write(&unrelated, b"keep").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(std::fs::read(unrelated).unwrap(), b"keep"); + assert_eq!(file_names(&dest), ["Alpha-Artboard-1.vectorcraft", "Alpha-Artboard-2.vectorcraft", "Alpha-photo.png", "Alpha.vectorcraft"]); + } + + #[test] + fn batch_separate_artboards_reserves_prior_output_names() { + let dest = tmp("choice-separate-reserved"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 20, "artboards": 2})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha"})).unwrap(); + s.execute("dataset.new", &json!({"name": "Alpha-Artboard-1"})).unwrap(); + let r = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", + "destinationFolder": dest.to_string_lossy(), + "commands": [{"command": "document.save", "params": {"separateArtboards": true}}] + }), + ) + .unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + assert!(dest.join("Alpha-Artboard-1.vectorcraft").exists()); + assert!(dest.join("Alpha-Artboard-1-2.vectorcraft").exists()); + } + + #[test] + fn batch_does_not_probe_a_denied_destination() { + let allowed = tmp("probe-allowed"); + let denied = tmp("probe-denied"); + std::fs::write(denied.join("Alpha.svg"), b"private").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[allowed.as_path()], &[allowed.as_path()]).unwrap().unwrap(); + let steps = [json!({"command": "document.export", "params": {"format": "svg"}})]; + let folder = denied.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", + }; + crate::file_access::confine(Some(&roots), || { + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Alpha"] + ); + let mut s = with_data_sets(&["Alpha"]); + let result = s + .execute( + "action.batch", + &json!({ + "source": "datasets", "datasetFileNaming": "dataSetName", "destination": "none", + "destinationFolder": folder, "overrideExport": true, + "commands": steps, + }), + ) + .unwrap(); + assert!(!result.to_string().contains("Alpha-2"), "{result}"); + }); + } + + #[test] + fn batch_does_not_probe_unknown_format_paths() { + let root = tmp("probe-format"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside"), b"private").unwrap(); + for format in ["../outside", "x/../../outside", "..\\..\\outside"] { + let steps = [json!({"command": "document.export", "params": {"format": format}})]; + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &steps, + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", + }; + assert_eq!( + dataset_stems(&["Alpha".into()], "source", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)) + .unwrap_or_else(|e| panic!("{format}: {e}")), + ["Alpha"], + "{format}" + ); + assert_eq!(rewrite_paths(&steps, false, true, Some(&folder), "Alpha", "vectorcraft"), steps, "{format}"); + } + } + + #[test] + fn batch_probe_and_dot_names_stay_in_destination() { + let root = tmp("probe-parent"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + let run = Run { + label: "Test", + steps: &[], + stop_on_error: true, + override_save: true, + override_export: true, + destination: "none", + dest_folder: Some(&folder), + dataset_file_naming: "fileDataSetName", + }; + assert_eq!( + dataset_stems(&[".".into(), "..".into()], ".", "dataSetName", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001", "Untitled002"] + ); + assert_eq!( + dataset_stems(&["Alpha".into()], "..", "fileNumber", &run, &vectorcraft_doc::Document::new(100.0, 80.0)).unwrap(), + ["Untitled001"] + ); + let output = root.join("named"); + let mut s = with_data_sets(&[".", ".."]); + let r = named_batch(&mut s, &output, Some("dataSetName")); + assert_eq!(r["failed"], 0, "{r}"); + assert_eq!(file_names(&output), ["Untitled001.vectorcraft", "Untitled002.vectorcraft"]); + } + + #[test] + fn batch_probe_rejects_parent_escape() { + let root = tmp("probe-parent-only"); + let folder = root.join("out"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(root.join("outside.svg"), b"private").unwrap(); + let folder = folder.to_string_lossy().into_owned(); + assert!(!dataset_output_exists( + Some(&folder), + "../outside", + &[DatasetOutput { ext: "svg".into(), artboards: false, joiner: "-" }], + &vectorcraft_doc::Document::new(100.0, 80.0), + )); + } + + #[test] + fn batch_rejects_unknown_data_set_naming_but_ignores_it_for_folders() { + let mut s = with_data_sets(&["Alpha"]); + let e = s + .execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})) + .unwrap_err(); + let msg = e.to_string(); + for value in ["fileNumber", "fileDataSetName", "dataSetName"] { + assert!(msg.contains(value), "{msg}"); + } + assert!( + s.execute("action.batch", &json!({"source": "datasets", "datasetFileNaming": 7, "commands": [{"command": "object.unlockAll"}]})).is_err() + ); + let src = tmp("folder-ignore-src"); + write_svg(&src, "one.svg", "#f00"); + let r = s.execute("action.batch", &json!({"source": "folder", "folder": src.to_string_lossy(), "datasetFileNaming": "other", "commands": [{"command": "object.unlockAll"}]})).unwrap(); + assert_eq!(r["failed"], 0, "{r}"); + } + #[test] fn batch_keeps_data_set_files_inside_the_destination_folder() { let root = tmp("set-names-root"); diff --git a/crates/engine/src/cmd/fileio/affinity.rs b/crates/engine/src/cmd/fileio/affinity.rs index 671bc04b63..c8ef3235ec 100644 --- a/crates/engine/src/cmd/fileio/affinity.rs +++ b/crates/engine/src/cmd/fileio/affinity.rs @@ -12,7 +12,7 @@ use serde_json::json; use vectorcraft_affinity::model::{self as af, Align as AfAlign, Blend, Kind, Pixels}; use vectorcraft_affinity::paint::{self as ap, Cap, GradientKind as AfKind, Join}; use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; -use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, Effect, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer}; +use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, Effect, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile}; use vectorcraft_doc::geom::{FillRule, PathData, shapes}; use vectorcraft_doc::text::{CharStyle, FirstBaseline, Justify, TextKind, TextObject, TextRun, VerticalAlign}; use vectorcraft_doc::{Artboard, Document, ImageObject, LayerColor, Node, NodeKind, OpacityMask}; diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs index 0375ff39e4..2e93342279 100644 --- a/crates/engine/src/cmd/fileio/affinity/nodes.rs +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -186,14 +186,19 @@ impl Builder { return Some(Arc::new(g)); }; self.outline_text(&n.effects, &mut text); - let mut node = self.base(n, NodeKind::Text(Box::new(text))); - node.opacity *= alpha; - if !children.is_empty() { - let mut kids = vec![Arc::new(node)]; + if children.is_empty() { + let mut node = self.base(n, NodeKind::Text(Box::new(text))); + node.opacity *= alpha; + node + } else { + // Text clips its children as a shape does: the type is the clipping path, its + // characters' fill behind the clipped art and their stroke over it. + let mut clip = Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(text))); + clip.opacity = alpha; + let mut kids = vec![Arc::new(clip)]; kids.extend(children); - node = Node::group(self.doc.alloc_id(), kids); + self.base(n, NodeKind::Group { children: kids, clip: true }) } - node } Kind::Table(t) => { let mut kids = self.table(t, to_doc); diff --git a/crates/engine/src/cmd/fileio/affinity/paint.rs b/crates/engine/src/cmd/fileio/affinity/paint.rs index ce798dcfbb..ed2b44ad3a 100644 --- a/crates/engine/src/cmd/fileio/affinity/paint.rs +++ b/crates/engine/src/cmd/fileio/affinity/paint.rs @@ -4,7 +4,7 @@ use super::text::Placement; use super::{ AfKind, Affine, Appearance, AppearanceItem, Arc, BezPath, Builder, Cap, Color, Dash, Effect, FillLayer, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, ImageObject, Join, LineCap, LineJoin, NodeKind, Paint, PathData, Pixels, Point, StrokeAlign, StrokeLayer, - TextObject, Vec2, af, ap, json, + TextObject, Vec2, WidthProfile, af, ap, json, }; impl Builder { @@ -232,6 +232,7 @@ impl Builder { offset: phase * self.k, align_corners: false, }); + l.profile = s.profile.as_ref().map(|p| WidthProfile { points: p.iter().map(|&(t, w)| (t, w, w)).collect() }); Some(l) } diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0c38079dff..f80302eee3 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,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; 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, after a central {stem}.eps of the whole document when there are two or more and art shows; 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), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), 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, after a central {stem}.eps of the whole document when there are two or more and art shows; 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 ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,