Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend

# Conflicts:
#	docs/target-app-parity.md
#	docs/ui-parity.md
This commit is contained in:
ncic committed 2026-10-31 18:35:28 +01:00
commit 4cd623df96
431 files changed
+41539 -2549

No files matched your search

+5 -8
View File
@@ -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,20 +72,17 @@ 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.<username>]` 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.
+1 -1
View File
@@ -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=<craft-fonts checkout>` (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-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them.
+3 -3
View File
@@ -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.
Generated
+66 -63
View File
@@ -217,7 +217,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
"wl-clipboard-rs",
"x11rb",
]
@@ -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",
]
@@ -763,9 +763,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",
]
@@ -1047,7 +1047,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"chrono",
"dunce",
@@ -1563,7 +1563,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1888,7 +1888,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",
]
@@ -3618,7 +3618,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3900,7 +3900,7 @@ dependencies = [
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix 1.1.5",
"rustix 1.1.6",
"windows-sys 0.61.2",
]
@@ -4140,7 +4140,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4489,15 +4489,15 @@ 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",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4556,7 +4556,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5097,9 +5097,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",
]
@@ -5142,7 +5142,7 @@ dependencies = [
"libc",
"log",
"memmap2",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"wayland-backend",
"wayland-client",
@@ -5415,10 +5415,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.59.0",
"rustix 1.1.6",
"windows-sys 0.61.2",
]
[[package]]
@@ -6037,7 +6037,7 @@ dependencies = [
[[package]]
name = "vectorcraft"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"arboard",
"block2 0.6.2",
@@ -6062,8 +6062,10 @@ dependencies = [
"raw-window-handle",
"rfd",
"serde_json",
"smithay-clipboard",
"socket2",
"vectorcraft-engine",
"vectorcraft-render",
"vectorcraft-text",
"vectorcraft-ui-egui",
"wayland-backend",
@@ -6080,7 +6082,7 @@ dependencies = [
[[package]]
name = "vectorcraft-affinity"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"crc32fast",
"flate2",
@@ -6091,7 +6093,7 @@ dependencies = [
[[package]]
name = "vectorcraft-brush"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"kurbo 0.13.1",
"serde",
@@ -6103,7 +6105,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cad"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6119,7 +6121,7 @@ dependencies = [
[[package]]
name = "vectorcraft-cli"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"log",
"objc2-core-foundation",
@@ -6141,7 +6143,7 @@ dependencies = [
[[package]]
name = "vectorcraft-color"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"kurbo 0.13.1",
"moxcms",
@@ -6153,7 +6155,7 @@ dependencies = [
[[package]]
name = "vectorcraft-doc"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"chrono",
"hayro-ccitt",
@@ -6172,7 +6174,7 @@ dependencies = [
[[package]]
name = "vectorcraft-effects"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6188,7 +6190,7 @@ dependencies = [
[[package]]
name = "vectorcraft-engine"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"craft-docpath",
"crc32fast",
@@ -6198,7 +6200,7 @@ dependencies = [
"log",
"proptest",
"roxmltree 0.21.2",
"rustix 1.1.5",
"rustix 1.1.6",
"ruzstd",
"serde",
"serde_json",
@@ -6227,7 +6229,7 @@ dependencies = [
[[package]]
name = "vectorcraft-eps"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"fax",
"flate2",
@@ -6251,11 +6253,11 @@ dependencies = [
[[package]]
name = "vectorcraft-format"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"flate2",
"proptest",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -6266,7 +6268,7 @@ dependencies = [
[[package]]
name = "vectorcraft-geom"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"kurbo 0.13.1",
"proptest",
@@ -6278,7 +6280,7 @@ dependencies = [
[[package]]
name = "vectorcraft-mcp"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"image",
"log",
@@ -6297,7 +6299,7 @@ dependencies = [
[[package]]
name = "vectorcraft-metafile"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6311,7 +6313,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pathops"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
@@ -6323,7 +6325,7 @@ dependencies = [
[[package]]
name = "vectorcraft-pdf"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"aes",
"chrono",
@@ -6355,7 +6357,7 @@ dependencies = [
[[package]]
name = "vectorcraft-plugins"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"serde",
"serde_json",
@@ -6369,7 +6371,7 @@ dependencies = [
[[package]]
name = "vectorcraft-render"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"flate2",
"gif",
@@ -6381,6 +6383,7 @@ dependencies = [
"psd",
"serde_json",
"tiff",
"unicode-general-category",
"vectorcraft-brush",
"vectorcraft-color",
"vectorcraft-doc",
@@ -6398,14 +6401,14 @@ dependencies = [
[[package]]
name = "vectorcraft-scriptcheck"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"proptest",
]
[[package]]
name = "vectorcraft-svg"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"craft-docpath",
"flate2",
@@ -6430,7 +6433,7 @@ dependencies = [
[[package]]
name = "vectorcraft-testkit"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"fax",
"image",
@@ -6448,7 +6451,7 @@ dependencies = [
[[package]]
name = "vectorcraft-text"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"harfrust 0.13.3",
"icu_segmenter",
@@ -6469,7 +6472,7 @@ dependencies = [
[[package]]
name = "vectorcraft-three-d"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
@@ -6477,7 +6480,7 @@ dependencies = [
[[package]]
name = "vectorcraft-tools"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6493,7 +6496,7 @@ dependencies = [
[[package]]
name = "vectorcraft-trace"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"image",
"kurbo 0.13.1",
@@ -6505,7 +6508,7 @@ dependencies = [
[[package]]
name = "vectorcraft-ui-egui"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"bytemuck",
"craft-keymap",
@@ -6516,7 +6519,7 @@ dependencies = [
"egui_kittest",
"image",
"log",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_json",
"toml",
@@ -6543,7 +6546,7 @@ dependencies = [
[[package]]
name = "vectorcraft-web"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"eframe",
"egui",
@@ -6809,7 +6812,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
dependencies = [
"cc",
"downcast-rs",
"rustix 1.1.5",
"rustix 1.1.6",
"scoped-tls",
"smallvec",
"wayland-sys",
@@ -6822,7 +6825,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",
]
@@ -6844,7 +6847,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",
]
@@ -7182,7 +7185,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -7519,7 +7522,7 @@ dependencies = [
"libc",
"log",
"os_pipe",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"tree_magic_mini",
"wayland-backend",
@@ -7578,7 +7581,7 @@ dependencies = [
"libc",
"libloading",
"once_cell",
"rustix 1.1.5",
"rustix 1.1.6",
"x11rb-protocol",
]
@@ -7620,7 +7623,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -7674,7 +7677,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
version = "0.18.0"
version = "0.19.0"
dependencies = [
"serde_json",
]
@@ -7724,7 +7727,7 @@ dependencies = [
"hex",
"libc",
"ordered-stream",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_repr",
"tracing",
+2 -2
View File
@@ -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.19.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -20,7 +20,7 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c
# 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: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }
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" }
+12 -4
View File
@@ -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-10-31 · **Change:** minor (Progress log rows for the Arrange Tools add-on, Export for Screens as the reference app's dialog and the 2026-10-31 community landings; 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,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 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 +148,7 @@ 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. |
@@ -183,7 +188,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 undLine truncated
| 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 DisLine truncated
| 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 |
@@ -193,12 +198,15 @@ 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-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. |
@@ -219,7 +227,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 |
+3 -2
View File
@@ -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.
+7
View File
@@ -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();
+2 -2
View File
@@ -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<f64, String> {
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;
+9 -1
View File
@@ -54,7 +54,11 @@ 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.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "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
@@ -92,6 +96,10 @@ x11rb = { version = "0.13", default-features = false, features = ["xinput"] }
# 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
+11 -7
View File
@@ -1,6 +1,8 @@
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
use super::gpu;
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};
@@ -105,11 +107,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);
}
@@ -147,15 +151,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<String>) {
for f in files {
+316 -22
View File
@@ -9,8 +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. A clipboard that can't
//! be opened is tried again after a wait that grows to a minute, not each time Paste asks.
//! 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).
@@ -20,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<dyn SystemClipboard> {
/// 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<std::sync::Arc<winit::window::Window>>) -> Box<dyn SystemClipboard> {
#[cfg(windows)]
let cb = Box::<win::Clipboard>::default();
let cb = {
let _ = window;
Box::<win::Clipboard>::default()
};
#[cfg(not(windows))]
let cb = Box::<portable::Clipboard>::default();
let cb = Box::new(portable::Clipboard::new(window));
cb
}
@@ -307,10 +313,12 @@ 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};
@@ -322,6 +330,109 @@ mod portable {
Image(usize, usize),
}
/// 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<winit::window::Window>>) -> Result<Self, String> {
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<String, String> {
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<arboard::ImageData<'static>, 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<std::path::PathBuf> {
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<B>(arboard: impl FnOnce() -> Result<B, String>, wayland: impl FnOnce() -> Result<B, &'static str>) -> Result<B, String> {
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)]
@@ -348,7 +459,7 @@ mod portable {
}
/// A handle opened on first use and kept, or after a failure opened again only once its wait is
/// over: where the clipboard can't be opened, asking a few times a second must not reconnect each time.
/// over: where neither backend opens, asking a few times a second must not reconnect each time.
pub(super) struct Reopen<B> {
handle: Option<B>,
failed: Option<Failed>,
@@ -415,20 +526,20 @@ mod portable {
pub struct Clipboard {
/// Kept open: on Linux the copied data lives as long as the handle does.
cb: Reopen<arboard::Clipboard>,
cb: Reopen<Backend>,
/// The app window, for the Wayland core protocol (on its connection).
window: Option<Arc<winit::window::Window>>,
ours: Option<Ours>,
}
impl Default for Clipboard {
fn default() -> Self {
Self { cb: Reopen::new(&UNAVAILABLE_LOGGED), ours: None }
}
}
impl Clipboard {
fn cb(&mut self, asker: Asker) -> Result<&mut arboard::Clipboard, String> {
let open = || arboard::Clipboard::new().map_err(|e| e.to_string());
self.cb.get(asker, Instant::now(), open, |_| "arboard").ok_or_else(|| "no system clipboard".to_string())
pub fn new(window: Option<Arc<winit::window::Window>>) -> 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())
}
}
@@ -442,16 +553,16 @@ mod portable {
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
}
};
@@ -470,7 +581,7 @@ mod portable {
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
let cb = self.cb(Asker::User).ok()?;
if let Some(f) = cb.get().file_list().ok().and_then(|paths| copied_file(paths, mimes)) {
if let Some(f) = copied_file(cb.file_list(), mimes) {
return Some(f);
}
mimes.iter().find_map(|m| {
@@ -608,6 +719,26 @@ mod portable {
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);
@@ -623,6 +754,169 @@ mod portable {
}
}
/// 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<winit::window::Window>,
}
/// The read worker's clipboard and the window whose connection it uses, dropped in that order.
struct Loader {
cb: smithay_clipboard::Clipboard,
_window: Arc<winit::window::Window>,
}
impl Loader {
fn load(&self) -> Result<String, String> {
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<winit::window::Window>) -> Option<Self> {
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<String, String> {
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<Result<String, String>>,
/// 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<String, String> + Send + 'static) -> Option<Self> {
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<String, String> {
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("<svg/>".into())).unwrap();
assert_eq!(loads.get(Duration::from_secs(5)), Ok("<svg/>".to_string()));
assert_eq!(loads.get(Duration::from_secs(5)), Ok("<svg/>".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()));
}
}
}
/// The macOS pasteboard's vector art and bitmaps as they are (arboard reads text, and of the
/// pictures TIFF only, decoded).
#[cfg(target_os = "macos")]
+4 -2
View File
@@ -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);
+33 -3
View File
@@ -1,7 +1,10 @@
//! VectorCraft desktop app.
//!
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
//! [--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`).
@@ -45,11 +48,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;
@@ -118,7 +125,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:
@@ -142,6 +151,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 +164,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 +194,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();
@@ -452,7 +475,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`).
@@ -473,6 +499,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"))]
+386
View File
@@ -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<Vec<String>> = Mutex::new(Vec::new());
/// The UI to wake when files arrive (unset until the window exists; the first frame opens them).
static UI: OnceLock<egui::Context> = 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<Primary>),
}
/// 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<String> {
std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner))
}
fn queue(files: Vec<String>) {
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<Endpoint> {
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::<io::Result<Vec<_>>>()?;
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<String>) + Send + 'static) -> Option<Primary> {
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<String>) + Send + 'static) -> io::Result<Primary> {
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<Vec<String>> {
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<Value> {
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, "<svg/>").unwrap();
let file = file.to_string_lossy().into_owned();
(dir.join(FILE_NAME), dir, file)
}
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
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<Value> {
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);
}
}
+40
View File
@@ -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<usize> {
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}");
}
}
+1 -3
View File
@@ -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
+11 -5
View File
@@ -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"
@@ -183,3 +180,12 @@ 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
+1 -1
View File
@@ -17,7 +17,7 @@ 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) |
+19 -13
View File
@@ -98,20 +98,26 @@ pub fn utf8(text: &str) -> F {
}
pub fn document(blocks: Vec<F>, frame: bool, dpi: f64, transform: [f64; 6]) -> Vec<u8> {
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<F>, frame: bool, dpi: f64, transform: [f64; 6], children: Vec<F>) -> Vec<u8> {
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))])),
(
+69 -2
View File
@@ -41,7 +41,8 @@ const MASK_STEPS: usize = 32;
/// 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.
/// 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<Node> {
let mut out = n.clone();
out.appearance.scale_strokes(width_scale);
@@ -63,9 +64,21 @@ 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)
}
/// 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<Node>) {
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 {
@@ -338,7 +351,8 @@ fn affine_fit(f: &dyn Fn(Point) -> Point, b: Rect, tol: f64) -> Option<Affine> {
/// 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<Node> {
let mut out = prepared(n, width_scale)?;
out.transform(a, false);
@@ -365,6 +379,7 @@ fn prepared(n: &Node, width_scale: f64) -> Option<Node> {
}
_ => return None,
}
map_mask(&mut out, |art| prepared(art, width_scale));
Some(out)
}
@@ -416,6 +431,7 @@ fn widen_strokes(n: &Node, factor: &dyn Fn(&Node) -> 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
}
@@ -590,6 +606,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
}
@@ -1133,4 +1152,52 @@ mod tests {
}
}
}
/// 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");
}
}
+28
View File
@@ -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.
+5 -2
View File
@@ -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,
+142 -9
View File
@@ -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<CircularSub> {
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<EllipticalSub> {
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::<f64>() * 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<Vec<Point>> {
// Far outside any drawing, a curve flattens to millions of points at this tolerance.
@@ -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<f64> = 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(&region.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<f64>) {
@@ -787,7 +872,8 @@ impl<'a> Scene<'a> {
let pts: Vec<Point> = 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) {
+319 -7
View File
@@ -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<i32> = [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<String> { 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<u32> = 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<i32> = 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::<Vec<_>>(), ["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<kurbo::PathEl> = 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<Point>| {
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::<Vec<_>>(), ["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<Dash>| {
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 {
+15 -3
View File
@@ -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);
+9
View File
@@ -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> {
Self::PRESETS.iter().find(|p| p.id == id).map(|p| Self { points: p.points.to_vec() })
+39 -1
View File
@@ -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::<f64>().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]
+3 -2
View File
@@ -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<Node> {
m.quads(n)
m.pieces(n)
.into_iter()
.map(|q| {
let mut ap = Appearance::default();
+130 -4
View File
@@ -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<Point>,
pub color: Color,
pub opacity: f32,
}
/// Create Gradient Mesh → Appearance.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MeshAppearance {
@@ -170,11 +179,22 @@ pub(super) fn grid_len(rows: u32, cols: u32) -> Option<usize> {
}
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
@@ -347,13 +367,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<MeshQuad> {
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 {
@@ -383,6 +410,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<MeshPiece> {
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<Point> {
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::<Option<Vec<Point>>>() 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<f32> {
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() {
+3 -2
View File
@@ -683,8 +683,8 @@ 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 {
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));
@@ -693,6 +693,7 @@ 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())
|| effects(&self.appearance.effects)
|| self
.appearance
+29
View File
@@ -339,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};
+5 -3
View File
@@ -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());
}
}
}
+13 -6
View File
@@ -18,8 +18,8 @@ pub trait ColorVisitor {
fn image(&mut self, key: &str) -> Option<String>;
}
/// 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;
+28 -8
View File
@@ -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<char>) -> 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<char>, quote_opened: Option<bool>) -> 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<char>) -> 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);
@@ -326,6 +334,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() };
+7
View File
@@ -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");
}
+4 -1
View File
@@ -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())
}
}
+9
View File
@@ -2,5 +2,14 @@
//!
//! - [`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;
+10 -4
View File
@@ -1,6 +1,6 @@
//! Color Effects (a built-in add-on): live Exposure, Desaturate 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.
//! 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};
@@ -13,9 +13,10 @@ pub const EXPOSURE: &str = "addon.color.exposure";
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; 3] = [DESATURATE, EXPOSURE, INVERT];
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 {
@@ -28,6 +29,7 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
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…",
@@ -49,6 +51,8 @@ pub(crate) enum Adjust {
},
Desaturate,
Invert,
/// Duotone ([`super::duotone`]).
Duotone(super::duotone::Duotone),
}
impl Adjust {
@@ -61,6 +65,7 @@ impl Adjust {
},
DESATURATE => Adjust::Desaturate,
INVERT => Adjust::Invert,
DUOTONE => Adjust::Duotone(super::duotone::Duotone::parse(p)?),
_ => return None,
})
}
@@ -73,6 +78,7 @@ impl Adjust {
[(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),
}
}
}
+178
View File
@@ -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<bool> + 'a;
/// [`SwatchKinds`] of `d`'s swatch `name`.
pub fn swatch_kind(d: &Document, name: &str) -> Option<bool> {
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<String, bool> {
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<String>,
/// 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<Tone>,
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<Self> {
let tones: Vec<Tone> = 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<String>, 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;
+128
View File
@@ -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<String>, 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]));
}
+489
View File
@@ -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<EffectInfo> {
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<Self> {
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<u8>,
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<u8>, (w, h): (usize, usize), region: Rect, scale: f64, mono: bool, invert: bool) -> Option<Self> {
(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<usize> {
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<Item = Point> {
(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::<f64>() / 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<Self> {
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<Screen> {
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<PathData>> = 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<PathData>, 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<Arc<Node>> {
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<Node>;
static ART: OnceLock<ArtHook> = 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<Node> {
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::<Vec<_>>());
// 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);
}
}
+243
View File
@@ -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<EffectInfo> {
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<PathData> {
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;
+278
View File
@@ -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::<Vec<_>>(), 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::<Vec<_>>(), 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<f64> = 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<f64> = 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::<Vec<_>>(), 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);
}
+83 -26
View File
@@ -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};
@@ -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)]
@@ -92,6 +93,16 @@ enum Adjust {
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.
#[derive(Clone, Debug, PartialEq)]
pub struct ColorMap(Vec<Adjust>);
@@ -104,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<String>, 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.
@@ -124,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<ColorMap> {
let v: Vec<Adjust> =
@@ -233,12 +276,12 @@ impl Adjust {
}
/// `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));
@@ -248,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 == ';')
@@ -260,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 {
@@ -357,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<String> + '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)
@@ -378,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<Node> {
/// 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<Node> {
let mut m: Option<Node> = 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);
@@ -394,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));
}
}
@@ -406,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
}
@@ -423,13 +479,14 @@ pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option<Node> {
}
_ => n,
};
let kinds = crate::addons::duotone::swatch_kinds(d);
let mut hook = |key: &str, map: &ColorMap| -> Option<String> {
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)]
@@ -492,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());
@@ -517,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<String> = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect();
+5
View File
@@ -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<Node> {
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));
+2
View File
@@ -792,6 +792,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
}
}
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,
+1
View File
@@ -265,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(),
+4 -2
View File
@@ -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())
}
+26 -1
View File
@@ -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<AppearanceItem> {
let own: Vec<AppearanceItem> = 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<Vec<Facet>, String> {
let view = view_options(p);
match id {
@@ -320,7 +344,8 @@ pub fn solid_art(n: &Node) -> Option<Node> {
}
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<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
+5
View File
@@ -33,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;
@@ -244,6 +245,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());
@@ -613,6 +615,9 @@ 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};
+5 -1
View File
@@ -1,16 +1,20 @@
//! VectorCraft's built-in add-ons: extra tools beyond the standard menus, each a module of its own
//! with commands under `addon.<name>.*` (see `docs/mcp.md`).
mod arrange;
mod cleanup;
mod color;
mod pathtools;
mod pen;
use super::CommandSpec;
/// The commands of every built-in add-on.
pub fn specs() -> Vec<CommandSpec> {
let mut v = cleanup::specs();
let mut v = arrange::specs();
v.extend(cleanup::specs());
v.extend(color::specs());
v.extend(pathtools::specs());
v.extend(pen::specs());
v
}
+272
View File
@@ -0,0 +1,272 @@
//! 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. 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 serde_json::{Value, json};
use vectorcraft_doc::{NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_render::effects;
use super::super::edit::selected_roots;
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, 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;
pub fn specs() -> Vec<CommandSpec> {
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
),
]
}
/// 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<f64> {
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.
fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result<Option<u64>> {
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<Option<f64>> {
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<NodeId> = 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<OrientedBox> {
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
}
fn grid(s: &mut Session, p: &Value) -> Result<Value> {
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::<f64>() + 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<f64> {
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<Value> {
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<Value> {
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<NodeId> = 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::<Vec<_>>() }))
}
fn size(s: &mut Session, p: &Value) -> Result<Value> {
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() }))
}
@@ -0,0 +1,263 @@
//! 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::<Vec<_>>()})).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<NodeId> = 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<NodeId> = 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<NodeId> = 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"] {
assert!(!enabled(&s, c), "{c}");
}
assert!(!enabled(&Session::new(), "addon.arrange.swap"));
}
+10 -7
View File
@@ -1,10 +1,12 @@
//! 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. Its panel and its submenu, Object › Plug-ins › Artwork Cleanup, are the UI's.
//! 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};
@@ -16,9 +18,8 @@ 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, and the drift (pt) each step of it allows.
/// Simplify Anchors' tolerance by default.
const TOLERANCE: f64 = 20.0;
pub(super) const PT_PER_TOLERANCE: f64 = 0.02;
/// Rejoin Path Pieces' gap by default, and the widest (pt).
const GAP: f64 = 0.1;
const MAX_GAP: f64 = 6.0;
@@ -30,7 +31,7 @@ const FIX_ROUNDS: usize = 3;
const MAX_LISTED: usize = 1000;
pub fn specs() -> Vec<CommandSpec> {
vec![
let mut v = vec![
cmd!(
"addon.cleanup.simplify",
"Simplify Anchors (Keep Shape)…",
@@ -45,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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), 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",
"{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
),
@@ -85,7 +86,9 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
rejoin
),
]
];
v.extend(text::specs());
v
}
/// The paths (not guides) under `roots`, compound path members included.
@@ -119,7 +122,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
let changed: Vec<(NodeId, PathData)> = paths
.iter()
.filter_map(|(id, path)| {
let np = po::simplify_keep_shape(path, tolerance * PT_PER_TOLERANCE, protect);
let np = po::simplify_keep_shape(path, tolerance * po::PT_PER_TOLERANCE, protect);
(np != **path).then_some((*id, np))
})
.collect();
+32 -3
View File
@@ -235,17 +235,46 @@ fn is_plain(n: &Node) -> bool {
&& *n.extras() == NodeExtras::default()
}
/// Is `n` a plain path (full opacity, normal blending) identical to the object just below it?
/// 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 !matches!(n.kind, NodeKind::Path { .. }) || n.opacity < 1.0 || n.blend != BlendMode::Normal {
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 && b.kind == n.kind && b.appearance == n.appearance && b.opacity == n.opacity && b.blend == n.blend && b.extras() == n.extras()
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
}
@@ -226,6 +226,26 @@ fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() {
}
}
/// 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();
@@ -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<f64> = -1000.0..=10000.0;
pub fn specs() -> Vec<CommandSpec> {
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<Vec<NodeId>> {
fn visit(n: &Node, out: &mut Vec<NodeId>) {
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<Point> {
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<Point> {
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<Point> {
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<Self> {
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<usize> = 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<TextObject> {
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<ParaStyle> = 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<TextObject>)>) -> Result<Vec<u64>> {
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<Node> = 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<u64> {
ids.iter().map(|i| i.0).collect()
}
fn break_text(s: &mut Session, p: &Value) -> Result<Value> {
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<TextObject> = 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<Value> {
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<TextObject> = 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<TextObject, usize> {
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<f64> = 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<f64> = 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<f64> = 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<Value> {
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<(&Piece, &Node)>> = 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<&Piece>> = 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<NodeId>)> = 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<u64> = 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<Value> {
const C: &str = "addon.cleanup.joinText";
let d = &s.doc()?.doc;
let pieces: Vec<Piece> =
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<&Piece>> = 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<vectorcraft_doc::TextRun> = 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<NodeId> = 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<Value> {
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<Vec<NodeId>> {
let d = &s.doc()?.doc;
let ids: Vec<NodeId> = 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<Value> {
let ids: Vec<u64> = 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<Value> {
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<Value> {
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<Value> {
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 }))
}
@@ -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<NodeId> {
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::<String>(), now.iter().map(|g| g.0).collect::<String>());
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<Value, EngineError>) -> 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<String> = 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::<Vec<_>>(), [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<String> = 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::<Vec<_>>());
}
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:?}");
}
+100 -16
View File
@@ -1,28 +1,110 @@
//! Color Effects (`addon.color.*`), a built-in add-on: its live effects (Exposure, Desaturate and
//! Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as Filter writes
//! any colour adjustment into the colours themselves. Its panel and its submenu, Object › Plug-ins ›
//! Color Effects, are the UI's.
//! 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,
//! and Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print. Its panel and
//! its submenu, Object › Plug-ins › Color Effects, are the UI's.
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;
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, text_param};
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<CommandSpec> {
vec![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 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 → {changed}",
has_selection,
filter
)]
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
),
]
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
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<NodeId> = 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<Value> {
@@ -45,5 +127,7 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("ids".into(), json!(ids.iter().map(|i| i.0).collect::<Vec<_>>()));
}
let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…'));
recolor(s, &given, label, &|c| map.apply(c))
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))
}
@@ -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<f32> {
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<Self> {
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<Value> {
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<String>, _: &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;
@@ -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<NodeId>) {
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<bool> = 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::<Vec<_>>(), [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}");
}
+227
View File
@@ -87,3 +87,230 @@ fn bad_requests_are_refused() {
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<NodeId> {
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<u8> {
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", &params).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<usize> = ["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);
}
+77 -30
View File
@@ -1,8 +1,16 @@
//! 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 and Split / Add Points at Crossings. Its tools, panel and submenu (Object ›
//! Plug-ins › Path Precision Tools) are the tools crate's and the UI'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`]), and the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]).
//! 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;
@@ -18,7 +26,6 @@ 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 super::cleanup::PT_PER_TOLERANCE;
use crate::{EngineError, Result, Session};
/// The Anchor Eraser Brush's tolerance by default (the scale Simplify Anchors (Keep Shape) uses).
@@ -37,7 +44,7 @@ const MAX_EXTEND: f64 = 1e6;
const MAX_ADD: u64 = pt::MAX_ADDED_PER_SEGMENT as u64;
pub fn specs() -> Vec<CommandSpec> {
vec![
let mut v = vec![
cmd!(
"addon.pathtools.erase",
"Anchor Eraser Brush",
@@ -52,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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 → {id, length (pt)}",
"{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
),
@@ -70,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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 → {anchors}",
"{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
),
@@ -137,7 +144,20 @@ pub fn specs() -> Vec<CommandSpec> {
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
),
];
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.
@@ -240,7 +260,7 @@ fn erase(s: &mut Session, p: &Value) -> Result<Value> {
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 * PT_PER_TOLERANCE };
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 {
@@ -284,8 +304,8 @@ fn edit_whole(s: &mut Session, label: &str, changed: Vec<(NodeId, PathData)>) ->
// ---------- Extend Path ----------
/// The open subpath an `extend` request names: (path id, subpath index, its data).
fn open_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, SubPath)> {
/// 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;
@@ -294,15 +314,36 @@ fn open_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, Sub
}
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"))?;
if sp.closed || sp.anchors.len() < 2 {
return Err(bad(cmd, "the subpath has no ends to extend (it is closed or a single point)"));
}
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<Value> {
const C: &str = "addon.pathtools.extend";
let (id, si, sp) = open_subpath(s, p, C)?;
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,
@@ -324,22 +365,26 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {
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"))?;
if new != sp {
s.edit("Extend Path", |d, sel| {
let n = d.node(id).and_then(|n| n.path_data()).cloned().ok_or(EngineError::NoNode(id))?;
let mut np = n;
if let Some(slot) = np.subpaths.get_mut(si) {
*slot = new;
}
sel.anchors.remove(&id);
sel.segments.remove(&id);
set_path(d, id, np);
Ok(())
})?;
}
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<Value> {
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 {
@@ -351,7 +396,7 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
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()) {
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"))?;
@@ -419,10 +464,12 @@ fn edit_anchors(s: &mut Session, label: &str, cmd: &str, f: impl Fn(&mut SubPath
}
}
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(())
})?;
}
@@ -430,7 +477,7 @@ fn edit_anchors(s: &mut Session, label: &str, cmd: &str, f: impl Fn(&mut SubPath
}
/// A smoothing `ratio` param (default [`pt::SMOOTH_RATIO`]).
fn ratio(p: &Value, cmd: &str) -> Result<f64> {
pub(super) fn ratio(p: &Value, cmd: &str) -> Result<f64> {
let r = number_or(p, "ratio", pt::SMOOTH_RATIO, cmd)?;
let (lo, hi) = pt::SMOOTH_RATIO_RANGE;
if !(lo..=hi).contains(&r) {
@@ -575,7 +622,7 @@ fn add_points(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "added": added }))
}
fn close(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn close(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.close";
let mode = match text_param(p, "mode", C)? {
None => pt::CloseMode::Handles,
@@ -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<CommandSpec> {
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<Option<BTreeSet<usize>>> {
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::<Result<_>>()
.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<Vec<(NodeId, BTreeSet<usize>)>> {
let shared = anchors_param(p, cmd)?;
// Each path with its own `anchors`, or sharing the request's.
let mut own: Vec<Option<BTreeSet<usize>>> = vec![];
let ids: Vec<NodeId> = 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<usize>)>, radius: f64, kind: Option<CornerKind>) -> Result<Value> {
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::<Vec<_>>(),
"corners": corners.iter().map(|(_, c)| c.len()).sum::<usize>(),
});
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<Value> {
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::<CornerKind>(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<Value> {
let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?;
edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round))
}
@@ -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<u8> {
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<u8> {
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<Effect> =
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}");
}
@@ -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<CommandSpec> {
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<PathData> {
s.path().ok_or_else(|| bad(cmd, "the shape's numbers are out of range"))
}
fn create(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
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<u64> = 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 }))
}
@@ -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<CommandSpec> {
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<Value> {
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<Value> {
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<Item = (NodeId, &'a PathData)>) -> Result<SharedPoints> {
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<NodeId, Vec<(AnchorRef, Vec2)>> = 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);
}
}
@@ -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<Value> = 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<Point> {
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);
}
+402 -1
View File
@@ -4,7 +4,8 @@
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{LiveCorners, LiveShape, NodeId};
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{AnchorKind, PathData, Point};
use vectorcraft_tools::{PointerEvent, PointerKind};
@@ -273,3 +274,403 @@ fn crossings_add_anchors_or_cut_in_one_step() {
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_pathops::addons::pathtools::shapes::ParametricShape> {
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&quot;") && !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<LiveShape> {
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));
}
+349
View File
@@ -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<CommandSpec> {
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<Option<bool>> {
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> {
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<bool> {
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<Option<Point>> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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" }))
}
+287
View File
@@ -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<Value> = 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);
}
+107 -23
View File
@@ -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<CommandSpec> {
"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<CommandSpec> {
"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<CommandSpec> {
"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<Option<ItemTarget>> {
pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
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<Option<ItemTarget>> =
(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<bool> {
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<Value> {
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
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<Option<usize>> = match (selected, anchor) {
(ItemTarget::Item { index, .. }, Some(k)) => {
let mut order = ids.clone();
order.swap(0, k);
let mut per: Vec<Option<usize>> =
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<Value> {
}
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<Value> {
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<Value> {
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<Value> {
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));
+15 -15
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use vectorcraft_color::Swatch;
use vectorcraft_doc::ImageObject;
@@ -220,18 +222,16 @@ fn trace_params(s: &Session, c: &str, p: &Value) -> Result<tr::TraceParams> {
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<Vec<(Color, Paint)>> {
@@ -247,9 +247,7 @@ fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result<Vec<(Color, Pa
}
/// Document Library in Color mode: look the library's colors (or its color group's) up into
/// `params.swatches` → each one as traced (sRGB) with the paint to fill with. The document's
/// global and spot colors fill linked to their swatches ([`trace_swatch_paint`]); a swatch
/// library's colors fill unlinked. Errors name command `c`.
/// `params.swatches` → each one as traced (sRGB) with its unlinked paint. Errors name command `c`.
fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result<Vec<([u8; 3], Paint)>> {
if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary {
return Ok(vec![]);
@@ -557,6 +555,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
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) {
@@ -584,12 +588,8 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
*path = shape.to_path();
*live = Some(Box::new(shape));
}
// A library color fills with the swatch's own color (its model kept), linked to a
// global or spot swatch of the document.
let solid = library
.iter()
.find(|(rgb, _)| *rgb == tp.color)
.map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |l| l.1.clone());
let solid =
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
// Gradients: a path the tracer found to be a linear gradient is filled with it.
let paint = tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf));
n.appearance = match tp.stroke {
+20 -6
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Value> {
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<Value> {
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<NodeId> {
fn fill_color(n: &Node) -> Option<Color> {
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<Value> {
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<Value> {
};
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 }))
+12 -2
View File
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Value> {
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
+1 -1
View File
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
@@ -52,8 +52,8 @@ pub(super) fn grid_set(s: &mut Session, p: &Value) -> Result<Value> {
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<Vec<NodeId>> {
}
}
/// 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<Value> {
}
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<Value> {
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(())
+1 -1
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blob Brush",
[],
None,
"{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), 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
),
+28 -7
View File
@@ -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)
}
@@ -607,8 +610,22 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
if !(size.is_finite() && size > 0.0) {
return Err(bad(C, "size must be positive"));
}
let pressure = size_pressure(p, &samples, C)?;
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<f64>)> =
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<Point> = samples.into_iter().map(|(pt, _)| pt).collect();
let mapped_pts: Vec<Point> = 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
@@ -618,9 +635,12 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
};
let spine = |tol: Option<f64>| match tol {
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
None => PathData::single(SubPath::polyline(&pts, false)),
let spine = |tol: Option<f64>| {
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) => {
@@ -634,15 +654,16 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
}
}
// A click: one dab as wide as the pen pressed.
(Some((prof, variation)), false) => brush_region(&pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))),
(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(&pts, size))
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()));
}
+5 -3
View File
@@ -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<Anchor> {
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.
+18 -4
View File
@@ -69,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Vec<(NodeId, Option<usize>, 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() {
@@ -219,8 +219,9 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
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).
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());
Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed }))
}
@@ -646,6 +647,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);
@@ -721,6 +733,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
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 +747,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
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) });
+27 -4
View File
@@ -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
+22 -7
View File
@@ -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<Value> {
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<Value> {
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<Value> {
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,10 +444,10 @@ 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, 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<String>) -> Result<usize> {
@@ -458,12 +473,12 @@ 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`.
/// Whether `n` is or holds an image with see-through pixels (key in `keys`), a colorize paint,
/// 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<String>, on: bool) -> bool {
let on = on || blended(n);
match &n.kind {
NodeKind::Image(im) => on || keys.contains(&im.key),
NodeKind::Image(im) => on || keys.contains(&im.key) || n.extras().colorize.is_some(),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))),
}
}
+11 -6
View File
@@ -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);
+1 -1
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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 <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
"{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), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), 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 <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
has_doc,
screens::export_for_screens
),
+2 -2
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export DXF",
[],
None,
"{path?, version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (every stroke as its filled outline), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}",
"{path?, version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}",
has_doc,
export_dxf
)]
@@ -64,7 +64,7 @@ pub(super) const OPTIONS: &[FormatOption] = &[
name: "alterPaths",
ty: "boolean",
default: "false",
description: "Alter Paths for Appearance: every stroke as its filled outline",
description: "Alter Paths for Appearance: strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14",
},
FormatOption { name: "outlineText", ty: "boolean", default: "false", description: "type as glyph outlines (always with preserve: appearance)" },
FormatOption { name: "selectedOnly", ty: "boolean", default: "false", description: "only the selected objects, in their layers" },
+9 -6
View File
@@ -161,9 +161,8 @@ fn expand_appearances(d: &mut Document) {
}
}
/// Expand every layer's pattern fills that paint a transparent image into their tiles, so those
/// images flatten like any other transparent image. The writer would otherwise draw them opaque
/// over white.
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
/// opacity or blending into their tiles, so those images can be flattened.
fn expand_image_patterns(d: &mut Document) -> Result<()> {
let keys = super::super::flatten::see_through_images(d);
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
@@ -174,8 +173,8 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> {
}
/// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as
/// [`Document::walk`] counts). These are the images with see-through pixels, and the images
/// that have opacity or a blending mode of their own or, with `flatten`, of a group they are in.
/// [`Document::walk`] counts). These have see-through pixels or a colorize paint, or have opacity
/// or a blending mode of their own or, with `flatten`, of a group they are in.
/// With `flatten` only visible images are returned, because a hidden one (which the hidden objects
/// option may write) is written over white. With `omit` all of them are returned.
fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
@@ -184,7 +183,11 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
let mut at = 0;
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind
&& (keys.contains(&im.key) || n.opacity < 1.0 || n.blend != BlendMode::Normal || (mode == SeeThrough::Flatten && transparent(d, n.id)))
&& (keys.contains(&im.key)
|| n.extras().colorize.is_some()
|| n.opacity < 1.0
|| n.blend != BlendMode::Normal
|| (mode == SeeThrough::Flatten && transparent(d, n.id)))
{
out.push((at, n.id));
}
+60 -4
View File
@@ -197,6 +197,42 @@ fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option<Result<(D
)
}
/// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the
/// artboards is in the editing data alone, or that art past the page was clipped to it?
fn is_page_note(w: &str) -> bool {
w == vectorcraft_pdf::OFF_ARTBOARD_NOTE || w == vectorcraft_pdf::PAST_PAGE_NOTE
}
/// The document read from the editing data alone with its type as outlines when `opts` asks for
/// them (`textAs: outlines`): the page that would have them has none to give. Threaded type first
/// flows through its frames (the editing data gives a story in its first frame), and the outlined
/// frames leave their threads. Each outline group keeps its type's transparency, opacity mask and
/// effects.
pub(super) fn outlined_if_asked(mut doc: Document, warnings: Vec<String>, opts: &LoadOptions) -> (Document, Vec<String>) {
if opts.text_as != vectorcraft_pdf::TextAs::Outlines {
return (doc, warnings);
}
if !doc.text_threads.is_empty() {
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
}
let threaded = crate::cmd::threads::frames(&doc);
let mut texts = Vec::new();
doc.walk(|n| {
if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) {
texts.push(n.clone());
}
});
for t in texts {
let Some(o) = crate::cmd::flatten::outlined_text(&t) else { continue };
let o = Node { visible: t.visible, locked: t.locked, ..doc.reid(&o) };
if let Some(slot) = doc.node_mut(t.id) {
*slot = o;
}
}
crate::cmd::threads::leave_threads(&mut doc, &threaded);
(doc, warnings)
}
/// Does `doc` hold no art: only layers, with nothing in them?
fn draws_nothing(doc: &Document) -> bool {
let mut art = false;
@@ -282,10 +318,14 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// saved without its PDF part (#1387: else the page, which is the art). So too
// pages that draw nothing at all: there is no page art to check the layers
// against, and the empty page would lose all of it.
let alone = (r.only_text || draws_nothing(&r.document))
// A page is empty only when nothing on it was skipped (an image that can't be
// decoded draws nothing either): its notes are at most the page's own.
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
let alone = (r.only_text || empty)
.then(|| from_editing_data_alone(bytes, opts))
.flatten()
.and_then(|read| read.ok());
.and_then(|read| read.ok())
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts));
let (doc, warnings, read) = match alone {
Some((doc, warnings)) => (doc, warnings, true),
None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit),
@@ -299,6 +339,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let whole = LoadOptions { pages: None, ..opts.clone() };
from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts })
.unwrap_or(Err(e))
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts))
.inspect(|_| editing_data = true)
}
Err(e) => Err(e),
@@ -602,7 +643,11 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
reader.limits(limits);
let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?;
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
let turned = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff") && exif_orientation(bytes).is_some();
let kept = match f.id {
_ if turned => None,
"png" | "jpg" | "gif" | "webp" => Some(bytes.to_vec()),
"tiff" => vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, ppi),
_ => None,
@@ -621,13 +666,16 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
Some(read) => read.map_err(err)?,
None => {
use image::ImageDecoder as _;
let decoder = reader.into_decoder().map_err(err)?;
let mut decoder = reader.into_decoder().map_err(err)?;
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
image::DynamicImage::from_decoder(decoder).map_err(err)?.to_rgba8()
let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);
let mut img = image::DynamicImage::from_decoder(decoder).map_err(err)?;
img.apply_orientation(orientation);
img.to_rgba8()
}
},
};
@@ -637,6 +685,14 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
as_png(img, ppi)
}
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
/// it leaves them as stored, or the image has none.
pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
use image::ImageDecoder as _;
let mut decoder = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;
decoder.orientation().ok().filter(|o| *o != image::metadata::Orientation::NoTransforms)
}
/// `img` stored as a PNG that keeps the file's resolution.
fn as_png(img: image::RgbaImage, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
let size = img.dimensions();
+3 -3
View File
@@ -317,9 +317,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
/// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3,
/// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener`
/// options over it; images with see-through pixels count as transparency, rasterized areas are
/// clipped to their regions, and discarded overprints are dropped. `None` when nothing changes (or
/// the file keeps transparency).
/// options over it; images with see-through pixels and colorized images count as transparency,
/// rasterized areas are clipped to their regions, and discarded overprints are dropped. `None`
/// when nothing changes (or the file keeps transparency).
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<Option<Document>> {
if !set.pdf13() {
return Ok(None);
+32 -3
View File
@@ -309,6 +309,9 @@ struct ScreenParams {
/// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as
/// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`.
folders: Option<String>,
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or
/// `multiple` (a file per artboard, the default).
pdfs: Option<String>,
}
/// How exported files are sorted into folders.
@@ -389,6 +392,8 @@ struct Naming {
/// The counter counts files rather than items.
per_file: bool,
folders: Folders,
/// Export PDFs As › Single file.
single_pdf: bool,
}
impl Naming {
@@ -406,9 +411,14 @@ impl Naming {
Some("file") => true,
Some(c) => return Err(bad(C, format!("counterPer `{c}`: item or file"))),
};
let single_pdf = match o.pdfs.as_deref() {
None | Some("multiple") => false,
Some("single") => true,
Some(m) => return Err(bad(C, format!("pdfs `{m}`: single or multiple"))),
};
let filename = safe_name(&super::file_stem(title)).unwrap_or_else(|| "Untitled".into());
let pattern = o.name.clone().filter(|n| !n.trim().is_empty());
Ok(Self { pattern, prefix, filename, when, counter_start: o.counter_start.unwrap_or(1), per_file, folders })
Ok(Self { pattern, prefix, filename, when, counter_start: o.counter_start.unwrap_or(1), per_file, folders, single_pdf })
}
/// The sub-folder (`None` for the export folder itself) and the file name of the file row `r`
@@ -781,15 +791,34 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
// One step per item and row, the files a name collision skips included.
let steps = (items.len() * rows.len()) as u64;
let mut step = 0u64;
// Export PDFs As › Single file: with several artboards, a PDF row writes them all as the pages
// of one file, named as the document, with the first of them.
let artboards: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
for (index, item) in items.iter().enumerate() {
for r in &rows {
vectorcraft_doc::cancel::check()?;
vectorcraft_doc::cancel::progress(step, steps, &format!("Exporting file {} of {steps}", step + 1));
step += 1;
let (sub, file) = naming.file(item, index, files, r);
let single = artboards.as_ref().filter(|_| r.format.id == "pdf");
if single.is_some() && index > 0 {
continue;
}
let document = single.map(|_| Item {
name: naming.filename.clone(),
stem: naming.filename.clone(),
doc: item.doc.clone(),
artboard: None,
region: item.region,
every_artboard: None,
});
let (sub, file) = naming.file(document.as_ref().unwrap_or(item), index, files, r);
let name = sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}"));
let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key), o.name.is_some()) else { continue };
let bytes = if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) {
let bytes = if let Some(boards) = single {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
write(&item.doc, "pdf", &options)?
} else if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) {
// One page per artboard.
let mut options = r.options.clone();
options["range"] = json!("all");
+30
View File
@@ -837,3 +837,33 @@ fn a_failed_save_does_not_stamp_the_documents_dates() {
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty());
}
/// #4284: a photo whose EXIF orientation says the camera was turned places upright: its pixels
/// turned as the orientation says, its width and height swapped. One without keeps its own bytes.
#[test]
fn a_photo_places_the_way_its_exif_orientation_says() {
// 16 × 8, red on the left half.
let mut rgb = image::RgbImage::from_pixel(16, 8, image::Rgb([255, 255, 255]));
for y in 0..8 {
for x in 0..8 {
rgb.put_pixel(x, y, image::Rgb([220, 0, 0]));
}
}
let mut jpg = Vec::new();
image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap();
// An EXIF segment with Orientation 6: turn a quarter clockwise to show.
let exif: Vec<u8> =
[b"Exif\0\0".as_slice(), b"II", &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0], &[0, 0, 0, 0]].concat();
let mut turned = jpg[..2].to_vec();
turned.extend([0xff, 0xe1]);
turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
turned.extend(&exif);
turned.extend(&jpg[2..]);
let plain = raster_image(&jpg).unwrap();
assert_eq!((plain.width, plain.height, plain.blob.bytes.as_slice()), (16, 8, jpg.as_slice()), "a photo as taken keeps its bytes");
let img = raster_image(&turned).unwrap();
assert_eq!((img.width, img.height), (8, 16), "turned a quarter");
let px = image::load_from_memory(&img.blob.bytes).unwrap().to_rgb8();
let red = |p: &image::Rgb<u8>| p[0] > 150 && p[1] < 80;
assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12)), "the left half is on top");
}
+148 -1
View File
@@ -6,7 +6,7 @@ use std::io::Write as _;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_doc::{Node, NodeId, NodeKind};
use vectorcraft_testkit::ai;
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
@@ -576,6 +576,153 @@ fn an_ai_file_whose_pdf_part_draws_nothing_opens_from_its_editing_data() {
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
}
/// A page that draws nothing only because what it holds couldn't be read (an image that can't be
/// decoded) isn't an empty page: its notes stay, and the editing data isn't taken in its place
/// unchecked.
#[test]
fn a_page_whose_content_was_skipped_is_not_taken_for_an_empty_one() {
let broken = "q 100 0 0 50 0 0 cm BI /W 2 /H 2 /CS /RGB /BPC 8 /F /DCT ID notajpeg EI Q";
let mut s = Session::new();
let r = open(&mut s, "broken.ai", &ai::ai(&compressed(&ai::sample_data()), broken), json!({})).unwrap();
let warnings = r["warnings"].to_string();
assert_ne!(r["warnings"], json!([]), "the skipped image is told: {r}");
assert!(!warnings.contains("saved without PDF compatibility"), "{r}");
}
/// Editing data with one layer, "Art", holding one left-aligned story, "Hi", 14 pt Helvetica,
/// anchored at the canvas centre (the template box's centre), as the editing data's text document
/// gives it; compressed.
fn typed_data() -> Vec<u8> {
let story = "<< /0 << /0 (Hi\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 3 >> ] >> \
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 3 >> ] >> >> \
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>";
let document = format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n/1 << /1 [ {story} ] /2 << /1 12.0 >> >>\n"
);
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n";
let data = format!(
"%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\
%AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n",
ai::layer("Art", text),
lines.join("\n")
);
compressed(data.as_bytes())
}
/// How many text objects and how many paths the open document holds.
fn texts_and_paths(s: &Session) -> (usize, usize) {
let (mut texts, mut paths) = (0, 0);
s.doc().unwrap().doc.walk(|c| {
texts += usize::from(matches!(c.kind, NodeKind::Text(_)));
paths += usize::from(matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
});
(texts, paths)
}
/// Type asked for as outlines on a page that draws nothing: the editing data's type, outlined (the
/// page has none to give).
#[test]
fn an_empty_page_with_type_as_outlines_outlines_the_editing_datas_type() {
let file = ai::ai(&typed_data(), "");
let mut s = Session::new();
let r = open(&mut s, "typed.ai", &file, json!({})).unwrap();
assert_eq!(texts_and_paths(&s).0, 1, "by default the editing data's type is type: {r}");
let r = open(&mut s, "typed.ai", &file, json!({"textAs": "outlines"})).unwrap();
let (texts, paths) = texts_and_paths(&s);
assert_eq!(texts, 0, "no type left: {r}");
assert!(paths > 0, "the outlines are there: {r}");
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers");
}
/// Type asked for as outlines in a `.ai` saved without PDF compatibility (its page only a
/// placeholder): the editing data's type, outlined, as for an empty page.
#[test]
fn a_file_saved_without_its_pdf_part_with_type_as_outlines_outlines_its_type() {
let file = ai::ai(&typed_data(), PLACEHOLDER);
let mut s = Session::new();
let r = open(&mut s, "typed.ai", &file, json!({})).unwrap();
assert_eq!(texts_and_paths(&s).0, 1, "by default the editing data's type is type: {r}");
let r = open(&mut s, "typed.ai", &file, json!({"textAs": "outlines"})).unwrap();
let (texts, paths) = texts_and_paths(&s);
assert_eq!(texts, 0, "no type left: {r}");
assert!(paths > 0, "the outlines are there: {r}");
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers");
}
/// Type of the editing data outlined keeps its transparency, opacity mask and effects, and is
/// shown and locked as the type was.
#[test]
fn outlined_type_of_the_editing_data_keeps_its_transparency_and_effects() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
let mut doc = s.doc().unwrap().doc.as_ref().clone();
let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({}), visible: true };
{
let t = doc.node_mut(id).unwrap();
t.opacity = 0.5;
t.blend = vectorcraft_color::BlendMode::Multiply;
t.isolate = true;
t.locked = true;
t.name = Some("Title".into());
t.appearance.effects = vec![shadow.clone()];
}
let opts = LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() };
let (doc, _) = load::outlined_if_asked(doc, vec![], &opts);
let mut outlines = vec![];
doc.walk(|n| {
if n.extras().type_outlines {
outlines.push(n.clone());
}
});
let [o] = &outlines[..] else { panic!("one group of outlines: {outlines:?}") };
assert_eq!((o.opacity, o.blend, o.isolate), (0.5, vectorcraft_color::BlendMode::Multiply, true));
assert_eq!(o.appearance.effects, [shadow]);
assert!(o.locked && o.visible);
assert_eq!(o.name.as_deref(), Some("Title"));
}
/// Threaded type of the editing data, its story all in its first frame as the editing data gives
/// it, outlined: each frame's outlines show the text that flows into it.
#[test]
fn outlined_threaded_type_of_the_editing_data_shows_the_text_of_every_frame() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4);
let a =
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
// As the editing data gives it: the first frame holds the story, the second nothing yet.
let mut doc = s.doc().unwrap().doc.as_ref().clone();
let runs = |id: u64| match &doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("area type"),
};
let (shown, flowed) = (runs(a), runs(b));
let empty: Vec<_> = flowed.iter().take(1).map(|r| vectorcraft_doc::TextRun { text: String::new(), ..r.clone() }).collect();
for (id, put) in [(a, [shown, flowed].concat()), (b, empty)] {
if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind {
t.runs = put;
t.cached_bounds = None;
t.cached_baselines.clear();
}
}
let opts = LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() };
let (doc, _) = load::outlined_if_asked(doc, vec![], &opts);
let mut right = 0;
doc.walk(|n| {
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.geometric_bounds().is_some_and(|r| r.x0 >= 190.0) {
right += 1;
}
});
assert!(right > 0, "the second frame's text is outlined where it flows");
assert!(doc.text_threads.is_empty(), "outlined frames are in no thread: {:?}", doc.text_threads);
}
#[test]
fn editing_data_false_opens_only_what_the_page_prints() {
let mut s = Session::new();
+1 -1
View File
@@ -93,7 +93,7 @@ fn selected_only_exports_the_selection_in_its_layers() {
let line = s.execute("shape.line", &json!({"x1": 0, "y1": 90, "x2": 90, "y2": 90})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [line]})).unwrap();
let dxf = text(&s.execute("document.export", &json!({"format": "dxf", "selectedOnly": true})).unwrap());
assert_eq!(entities(&dxf), ["LWPOLYLINE"]);
assert_eq!(entities(&dxf), ["LINE"]);
assert!(dxf.contains("\n 2\nTop\n") && !dxf.contains("\n 2\nLayer 1\n"), "only the selection's layer");
s.execute("select.none", &json!({})).unwrap();
let e = s.execute("document.export", &json!({"format": "dxf", "selectedOnly": true})).unwrap_err().to_string();
@@ -811,3 +811,25 @@ fn the_document_remembers_its_export_settings() {
assert!(!plain.contains("export_settings") && !plain.contains("exportSettings"), "not written when empty");
assert!(vectorcraft_format::load(plain.as_bytes()).unwrap().export_settings.is_empty());
}
/// Export PDFs As › Single file: with several artboards, a PDF row writes them as the pages of one
/// file named after the document (raster rows still write a file per artboard); with one artboard
/// the PDF is that artboard's, as Multiple files writes it.
#[test]
fn single_file_pdfs_hold_every_chosen_artboard() {
let mut s = session(3);
let title = s.doc().unwrap().doc.title.clone();
let rows = json!([{"format": "png", "scale": "1x"}, {"format": "pdf"}]);
let r = export(&mut s, json!({"range": "1-2", "pdfs": "single", "formats": rows}));
let got = files(&r);
let pdf: Vec<&(String, Vec<u8>)> = got.iter().filter(|(n, _)| n.ends_with(".pdf")).collect();
assert_eq!(pdf.len(), 1, "{:?}", names(&r));
assert_eq!(pdf[0].0, format!("{title}.pdf"));
assert_eq!(vectorcraft_pdf::import(&pdf[0].1).unwrap().artboards.len(), 2, "one page per artboard");
assert_eq!(got.iter().filter(|(n, _)| n.ends_with(".png")).count(), 2);
let r = export(&mut s, json!({"range": "2", "pdfs": "single", "formats": [{"format": "pdf"}]}));
assert_eq!(names(&r), ["Artboard-2.pdf"]);
let r = export(&mut s, json!({"range": "1-2", "pdfs": "multiple", "formats": [{"format": "pdf"}]}));
assert_eq!(names(&r), ["Artboard-1.pdf", "Artboard-2.pdf"]);
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
}
+1 -1
View File
@@ -48,7 +48,7 @@ mod options;
mod presets;
mod report;
pub(crate) use analysis::see_through_images;
pub(crate) use analysis::{outlined_text, see_through_images};
pub(crate) use apply::flatten_document;
pub use commands::specs;
pub use options::FlattenOptions;
+1 -1
View File
@@ -51,7 +51,7 @@ impl Scratch {
}
/// Type as outlines painted like it ([`effects::outline_text`]), keeping its transparency.
pub(super) fn outlined_text(n: &Node) -> Option<Node> {
pub(crate) fn outlined_text(n: &Node) -> Option<Node> {
effects::outline_text(n).map(|g| Node { knockout: Knockout::Off, ..carry(n, g) })
}
+211 -11
View File
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Font",
[],
None,
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style) → {runs}",
"{from: {family, style?}, to: {family (any of its names; stored as the font's own family name), style?}, selectionOnly?} (style omitted: every style of the family / keep the closest style); text that is hidden or locked, in a hidden or locked group or layer, or on a locked artboard keeps its font → {runs, skipped?: the text objects left in the font, warning?: text (some text was left in its font, or the style set isn't available: its type is drawn in the family's closest style)}",
has_doc,
replace
),
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Text by Font",
[],
None,
"{family, style?} select the text objects using the font → {count}",
"{family, style?} select the text objects using the font that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard → {count}",
has_doc,
select_font
),
@@ -318,6 +318,24 @@ pub(super) fn substitution_warning(d: &Document) -> Option<String> {
/// [`substitution_warning`] for type set in `fonts`.
pub(super) fn substitution_warning_of(fonts: BTreeSet<UsedFont>) -> Option<String> {
substitutions(fonts, ("were written", "was drawn"))
}
/// The font (family, style, version) of character style `st`.
pub(super) fn font_of(st: &vectorcraft_doc::CharStyle) -> UsedFont {
(st.font_family.clone(), st.font_style.clone(), st.font_version.clone())
}
/// What `text.create`, `text.setStyle`, `text.setRangeStyle` and `text.replaceFont` say when the
/// fonts they set type in (`fonts`) don't draw it: the family isn't available (the fallback font
/// is drawn) or doesn't have that style (its closest style is drawn). `None` when all draw it.
pub(super) fn set_font_warning(fonts: BTreeSet<UsedFont>) -> Option<String> {
substitutions(fonts, ("are drawn", "is drawn"))
}
/// The warning for type set in `fonts`, with the verbs `written` and `drawn` (an export's are
/// `were written` and `was drawn`).
fn substitutions(fonts: BTreeSet<UsedFont>, (written, drawn): (&str, &str)) -> Option<String> {
let db = vectorcraft_text::FontDb::global();
let mut missing: Vec<String> = Vec::new();
let mut styles: BTreeSet<String> = BTreeSet::new();
@@ -325,7 +343,7 @@ pub(super) fn substitution_warning_of(fonts: BTreeSet<UsedFont>) -> Option<Strin
match db.resolve(&family, &style) {
None | Some((_, vectorcraft_text::FontMatch::Missing)) => missing.push(family),
Some((face, vectorcraft_text::FontMatch::Style)) => {
styles.insert(format!("{family} {style} was drawn in {} {}", face.family, face.style));
styles.insert(format!("{family} {style} {drawn} in {} {}", face.family, face.style));
}
Some(_) => {}
}
@@ -335,14 +353,14 @@ pub(super) fn substitution_warning_of(fonts: BTreeSet<UsedFont>) -> Option<Strin
let mut parts = Vec::new();
if !missing.is_empty() {
parts.push(format!(
"fonts that aren't available were written in the fallback font, {}: {} (install them, or replace them with Find Font)",
"fonts that aren't available {written} in the fallback font, {}: {} (install them, or replace them with Find Font)",
vectorcraft_text::FALLBACK_FAMILY,
missing.join(", ")
));
}
if !styles.is_empty() {
parts.push(format!(
"font styles that aren't available were written in the closest style: {} (pick a style the family has)",
"font styles that aren't available {written} in the closest style: {} (pick a style the family has)",
styles.into_iter().collect::<Vec<_>>().join(", ")
));
}
@@ -414,10 +432,20 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
Some((f, m)) if m != vectorcraft_text::FontMatch::Missing => f.family.clone(),
_ => return Err(bad(C, format!("font family `{tf}` is not available"))),
};
let ids = scope(s, bool_or(p, "selectionOnly", false))?;
let matches = |st: &vectorcraft_doc::CharStyle| {
st.font_family.eq_ignore_ascii_case(&ff) && fs.as_ref().is_none_or(|x| st.font_style.eq_ignore_ascii_case(x))
};
// Only text the Selection tool can reach changes: not hidden or locked, in a hidden or locked
// group or layer, or on a locked artboard. The text left in the font is counted.
let (ids, skipped) = {
let d = &s.doc()?.doc;
let editable = d.editable();
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, bool_or(p, "selectionOnly", false))?.into_iter().partition(|id| editable(*id));
let skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(|t| t.runs.iter().any(|r| matches(&r.style)))).count();
(ids, skipped)
};
// The fonts the replaced runs are set in, for the warning.
let mut set = BTreeSet::new();
let n = s.edit("Replace Font", |d, _| {
let mut n = 0;
for id in &ids {
@@ -435,6 +463,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
// Another font: none of the old one's versions or Variable Font settings.
r.style.font_version = None;
r.style.font_axes.clear();
set.insert(font_of(&r.style));
changed = true;
n += 1;
}
@@ -446,24 +475,42 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(n)
})?;
Ok(json!({ "runs": n }))
let mut out = json!({ "runs": n });
let mut warnings = Vec::new();
if skipped > 0 {
out["skipped"] = json!(skipped);
warnings.push(REPLACE_SKIPPED.to_string());
}
warnings.extend(set_font_warning(set));
if !warnings.is_empty() {
out["warning"] = json!(warnings.join("; "));
}
Ok(out)
}
/// What Replace Font says when it left text in the font that it can't reach.
const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced";
fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string();
let style = str_param(p, "style").map(str::to_string);
let ids = scope(s, false)?;
let d = &s.doc()?.doc;
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
// or layer, or on a locked artboard.
let editable = d.editable();
let hits: Vec<NodeId> = ids
.into_iter()
.filter(|id| {
text(d, *id).is_some_and(|t| {
t.runs.iter().any(|r| {
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x))
editable(*id)
&& text(d, *id).is_some_and(|t| {
t.runs.iter().any(|r| {
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|x| r.style.font_style.eq_ignore_ascii_case(x))
})
})
})
})
.collect();
drop(editable);
let n = hits.len();
s.select(|_, sel| sel.set(hits))?;
Ok(json!({ "count": n }))
@@ -568,6 +615,117 @@ mod tests {
assert!(s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Nope"}})).is_err());
let _ = a;
}
/// Select Text by Font leaves out hidden and locked text, and text inside a hidden or locked
/// group or layer. Text on a visible, unlocked template layer is selected.
#[test]
fn select_font_skips_hidden_and_locked_text() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, y: i32, font: &str| {
s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": font})).unwrap()["id"].as_u64().unwrap()
};
let mut ids = vec![];
for y in [20, 40, 60, 80, 100] {
ids.push(text(&mut s, y, "Source Serif 4"));
}
// Inter is used only by hidden or locked text.
let only_hidden = text(&mut s, 120, "Inter");
for (id, group, cmd) in [
(ids[1], false, "object.hide"),
(ids[2], false, "object.lock"),
(ids[3], true, "object.hide"),
(ids[4], true, "object.lock"),
(only_hidden, false, "object.hide"),
] {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
if group {
s.execute("object.group", &json!({})).unwrap();
}
s.execute(cmd, &json!({})).unwrap();
}
let mut layer_text = |props: &[Value]| {
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
let id = text(&mut s, 140, "Source Serif 4");
for p in props {
let mut p = p.clone();
p["id"] = json!(layer);
s.execute("layer.setProps", &p).unwrap();
}
id
};
layer_text(&[json!({"visible": false})]);
layer_text(&[json!({"locked": true})]);
// Template on locks the layer; unlocking it makes its text selectable again.
let template = layer_text(&[json!({"template": true}), json!({"locked": false})]);
assert_eq!(s.execute("select.font", &json!({"family": "Source Serif 4"})).unwrap()["count"], 2);
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(ids[0]), NodeId(template)]);
assert_eq!(s.execute("select.font", &json!({"family": "Inter"})).unwrap()["count"], 0);
assert!(s.doc().unwrap().selection.objects.is_empty());
}
/// Replace Font leaves hidden and locked text in its font, and text inside a hidden or locked
/// group or layer, and says so. Text on a visible, unlocked template layer is changed.
#[test]
fn replace_font_skips_hidden_and_locked_text() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, y: i32| {
s.execute("text.create", &json!({"x": 10, "y": y, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap()
};
let mut ids = vec![];
for y in [20, 40, 60, 80, 100] {
ids.push(text(&mut s, y));
}
for (id, group, cmd) in
[(ids[1], false, "object.hide"), (ids[2], false, "object.lock"), (ids[3], true, "object.hide"), (ids[4], true, "object.lock")]
{
s.execute("select.set", &json!({"ids": [id]})).unwrap();
if group {
s.execute("object.group", &json!({})).unwrap();
}
s.execute(cmd, &json!({})).unwrap();
}
let mut layer_text = |props: &[Value]| {
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
let id = text(&mut s, 140);
for p in props {
let mut p = p.clone();
p["id"] = json!(layer);
s.execute("layer.setProps", &p).unwrap();
}
id
};
ids.push(layer_text(&[json!({"visible": false})]));
ids.push(layer_text(&[json!({"locked": true})]));
// Template on locks the layer; unlocking it makes its text editable again.
let template = layer_text(&[json!({"template": true}), json!({"locked": false})]);
let family = |s: &Session, id: u64| text_family(s, id);
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r["runs"], 2, "{r}");
assert_eq!(r["skipped"], 6, "{r}");
assert_eq!(r["warning"], REPLACE_SKIPPED, "{r}");
assert_eq!(family(&s, ids[0]), "Source Sans 3");
assert_eq!(family(&s, template), "Source Sans 3");
for id in &ids[1..] {
assert_eq!(family(&s, *id), "Source Serif 4", "object {id}");
}
// The font stays in the document's list while the skipped text uses it.
let fams: Vec<String> =
s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap().to_string()).collect();
assert_eq!(fams, ["Source Sans 3", "Source Serif 4"]);
// Only skipped text left: nothing changes, and the warning says why.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!((r["runs"].clone(), r["skipped"].clone(), r["warning"].clone()), (json!(0), json!(6), json!(REPLACE_SKIPPED)), "{r}");
// A plain replacement carries no warning.
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Sans 3"}, "to": {"family": "Inter"}})).unwrap();
assert_eq!(r, json!({"runs": 2}));
}
/// The font family of text object `id`'s first run.
fn text_family(s: &Session, id: u64) -> String {
text(&s.doc().unwrap().doc, NodeId(id)).unwrap().runs[0].style.font_family.clone()
}
}
#[cfg(test)]
@@ -619,6 +777,48 @@ mod open_tests {
assert!(warnings.contains("Source Sans 3 Black Wide was drawn in Source Sans 3"), "{out}");
}
#[test]
fn setting_type_in_a_font_it_cant_draw_warns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let warning = |out: &Value| out["warning"].as_str().map(str::to_string);
let made = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi", "font": "Source Sans 3", "style": "Black Wide"})).unwrap();
assert!(warning(&made).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{made}");
let gone = s.execute("text.create", &json!({"x": 10, "y": 60, "text": "Gone", "font": "No Such Font Family"})).unwrap();
let w = warning(&gone).unwrap_or_default();
assert!(w.contains("No Such Font Family") && w.contains(vectorcraft_text::FALLBACK_FAMILY), "{gone}");
let plain = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Fine", "font": "Source Sans 3", "style": "Semibold"})).unwrap();
assert_eq!(warning(&plain), None, "{plain}");
let id = plain["id"].as_u64().unwrap();
let set = s.execute("text.setStyle", &json!({"ids": [id], "style": "Black Wide"})).unwrap();
assert!(warning(&set).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{set}");
let back = s.execute("text.setStyle", &json!({"ids": [id], "style": "Bold"})).unwrap();
assert_eq!(warning(&back), None, "{back}");
// Only the font the command set: the other objects' substitutes aren't its to report.
let size = s.execute("text.setStyle", &json!({"ids": [id], "size": 30})).unwrap();
assert_eq!(warning(&size), None, "{size}");
// Only the characters the command styles: with "Fi" in Black Wide, styling "ne" doesn't warn.
let first = s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "style": "Black Wide"})).unwrap();
assert!(warning(&first).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{first}");
let rest = s.execute("text.setRangeStyle", &json!({"id": id, "start": 2, "end": 4, "font": "Source Sans 3"})).unwrap();
assert_eq!(warning(&rest), None, "{rest}");
let range = s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "font": "No Such Font Family"})).unwrap();
assert!(warning(&range).is_some_and(|w| w.contains("No Such Font Family")), "{range}");
let replaced = s
.execute(
"text.replaceFont",
&json!({"from": {"family": "No Such Font Family"}, "to": {"family": "Source Sans 3", "style": "Black Wide"}}),
)
.unwrap();
assert!(warning(&replaced).is_some_and(|w| w.contains("Source Sans 3 Black Wide is drawn in Source Sans 3")), "{replaced}");
// Empty type: the font set is the one the next characters typed get.
let empty = s.execute("text.create", &json!({"x": 10, "y": 140, "text": ""})).unwrap()["id"].as_u64().unwrap();
let set = s.execute("text.setStyle", &json!({"ids": [empty], "style": "Black Wide"})).unwrap();
assert!(warning(&set).is_some_and(|w| w.contains("Black Wide")), "{set}");
let range = s.execute("text.setRangeStyle", &json!({"id": empty, "font": "No Such Font Family"})).unwrap();
assert!(warning(&range).is_some_and(|w| w.contains("No Such Font Family")), "{range}");
}
#[test]
fn opened_documents_have_exact_text_bounds() {
let mut s = Session::new();
+224
View File
@@ -0,0 +1,224 @@
//! The Gradient panel's presets: ready-made gradients grouped by theme, applied to the gradient
//! behind the active proxy in one click, and the user's own gradients saved beside them.
//!
//! The built-in presets are the gradient swatches of the built-in swatch libraries
//! ([`vectorcraft_color::libraries`]: the app's own computed palettes), each listed under its
//! library's name. Saved presets are kept with the preferences ([`crate::Prefs::gradient_presets`]),
//! so every document has them. A preset is the colour ramp (type, stops, method, dither), not a
//! placement: applying one edits the gradient in place, as `paint.editGradient` does.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::libraries::{GRADIENT_LIBRARIES, SWATCH_LIBRARIES, builtin_library};
use vectorcraft_color::{Gradient, GradientPaint, Paint};
use vectorcraft_tools::params::{gradient_params, stops_json};
use super::appearance::{edits_stroke, item_target};
use super::gradient::active_gradient;
use super::{CommandSpec, Result, Session, always, bad, cmd, has_doc, text_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "gradient.presets.list",
"Gradient Presets",
[],
None,
"{} → {presets: [{name, library: the built-in library (theme) it comes from, null for a saved one, builtIn, gradient: {kind, stops, method?, dither?} (as paint.setFill's `gradient`)}]} the Gradient panel's presets: the built-in ones by library, then the saved ones; names are unique",
always,
list
),
cmd!(
"gradient.presets.apply",
"Apply Gradient Preset",
[],
None,
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops and method, and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}",
has_doc,
apply
),
cmd!(
query "gradient.presets.save",
"Save Gradient Preset",
[],
None,
"{name?: (default: a new \"Gradient Preset N\"; unique, any case, and not a built-in preset's)} save the gradient behind the active proxy (paint.toggleActive picks Fill or Stroke) as a preset, kept with the preferences: its type, stops, method and dither (stops linked to a swatch keep their colour, unlinked) → {name}",
can_save,
save
),
cmd!(
query "gradient.presets.delete",
"Delete Gradient Preset",
[],
None,
"{name?: a saved preset (default: the saved preset the active proxy's gradient is)} remove a saved preset; built-in presets can't be deleted, and painted art keeps its gradient → {deleted}",
has_saved_presets,
delete
),
]
}
/// A gradient saved to the Gradient panel's presets ([`crate::Prefs::gradient_presets`]).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GradientPreset {
pub name: String,
pub gradient: Gradient,
}
/// A row of the Presets list: a built-in preset (with its library) or a saved one.
#[derive(Clone, Debug, PartialEq)]
pub struct GradientPresetEntry {
pub name: String,
/// The built-in library (theme) it comes from; `None` for a saved preset.
pub library: Option<&'static str>,
pub gradient: Gradient,
}
/// The built-in presets: every built-in library's gradient swatches, the gradient libraries first.
fn builtin_presets() -> impl Iterator<Item = GradientPresetEntry> {
GRADIENT_LIBRARIES.iter().chain(SWATCH_LIBRARIES).flat_map(|b| {
let lib = builtin_library(b.id);
let gradients: Vec<GradientPresetEntry> = lib
.iter()
.flat_map(|lib| lib.iter())
.filter_map(|w| match &w.paint {
Paint::Gradient(g) => Some(GradientPresetEntry { name: w.name.clone(), library: Some(b.name), gradient: g.gradient.clone() }),
_ => None,
})
.collect();
gradients
})
}
/// Do `a` and `b` have the same colour ramp (type, method, dither and stops), swatch links aside?
fn same_ramp(a: &Gradient, b: &Gradient) -> bool {
let stop = |x: &vectorcraft_color::GradientStop, y: &vectorcraft_color::GradientStop| {
(x.offset, x.color, x.opacity, x.midpoint) == (y.offset, y.color, y.opacity, y.midpoint)
};
(a.kind, a.method, a.dither) == (b.kind, b.method, b.dither)
&& a.stops.len() == b.stops.len()
&& a.stops.iter().zip(&b.stops).all(|(x, y)| stop(x, y))
}
/// `g` without links to document swatches: each linked stop keeps the colour it shows.
fn unlinked(g: &Gradient) -> Gradient {
let mut g = g.clone();
for s in &mut g.stops {
s.set_color(s.color, None);
}
g
}
impl Session {
/// The Gradient panel's presets: the built-in ones by library, then the saved ones.
pub fn gradient_presets(&self) -> Vec<GradientPresetEntry> {
let saved =
self.prefs.gradient_presets.iter().map(|p| GradientPresetEntry { name: p.name.clone(), library: None, gradient: p.gradient.clone() });
builtin_presets().chain(saved).collect()
}
/// The preset called `name` (any case).
pub fn gradient_preset(&self, name: &str) -> Option<GradientPresetEntry> {
let name = name.trim();
self.gradient_presets().into_iter().find(|e| e.name.eq_ignore_ascii_case(name))
}
/// The name Save Gradient Preset suggests: the first free "Gradient Preset N".
pub fn next_gradient_preset_name(&self) -> String {
let presets = self.gradient_presets();
(1..).map(|n| format!("Gradient Preset {n}")).find(|n| !presets.iter().any(|e| e.name.eq_ignore_ascii_case(n))).unwrap_or_default()
}
/// The name of the preset `g` is (its colour ramp, swatch links aside): a built-in one first,
/// then a saved one. Cheap enough for every frame: nothing is copied but the name found.
pub fn gradient_preset_name(&self, g: &Gradient) -> Option<String> {
let builtin = GRADIENT_LIBRARIES.iter().chain(SWATCH_LIBRARIES).find_map(|b| {
let lib = builtin_library(b.id)?;
lib.iter().find(|w| matches!(&w.paint, Paint::Gradient(x) if same_ramp(&x.gradient, g))).map(|w| w.name.clone())
});
builtin.or_else(|| self.prefs.gradient_presets.iter().find(|p| same_ramp(&p.gradient, g)).map(|p| p.name.clone()))
}
/// The saved preset the gradient behind the active proxy is (its colour ramp, links aside).
pub fn active_saved_gradient_preset(&self) -> Option<&str> {
let g = active_gradient(self)?;
self.prefs.gradient_presets.iter().find(|p| same_ramp(&p.gradient, &g.gradient)).map(|p| p.name.as_str())
}
}
fn can_save(s: &Session) -> std::result::Result<(), String> {
active_gradient(s).map(|_| ()).ok_or_else(|| "the active paint is not a gradient".into())
}
fn has_saved_presets(s: &Session) -> std::result::Result<(), String> {
if s.prefs.gradient_presets.is_empty() { Err("no saved gradient presets".into()) } else { Ok(()) }
}
/// `p`'s `name`: a string, required.
fn name_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
text_param(p, "name", cmd)?.ok_or_else(|| bad(cmd, "missing `name` (see gradient.presets.list)"))
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let rows: Vec<Value> = s
.gradient_presets()
.into_iter()
.map(|e| json!({"name": e.name, "library": e.library, "builtIn": e.library.is_some(), "gradient": gradient_params(&GradientPaint::new(e.gradient))}))
.collect();
Ok(json!({ "presets": rows }))
}
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "gradient.presets.apply";
let name = name_param(p, C)?;
let preset = s.gradient_preset(name).ok_or_else(|| bad(C, format!("no gradient preset `{name}` (see gradient.presets.list)")))?;
let stroke = edits_stroke(s, p, item_target(s, p, C)?, !s.fill_active, C)?;
let g = &preset.gradient;
let mut edit = p.clone();
let Some(o) = edit.as_object_mut() else { return Err(bad(C, "params must be an object")) };
o.remove("name");
o.insert("stroke".into(), json!(stroke));
o.insert("kind".into(), json!(g.kind.label().to_lowercase()));
o.insert("stops".into(), stops_json(&g.stops));
o.insert("method".into(), json!(g.method.label().to_lowercase()));
// Dither is a fill's (paint.editGradient refuses it on a stroke).
if !stroke {
o.insert("dither".into(), json!(g.dither));
}
let out = s.execute("paint.editGradient", &edit)?;
Ok(json!({"name": preset.name, "ids": out.get("ids").cloned().unwrap_or_else(|| json!([]))}))
}
fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "gradient.presets.save";
let g = active_gradient(s).ok_or_else(|| bad(C, "the active paint is not a gradient"))?;
let name = match text_param(p, "name", C)?.map(str::trim) {
None => s.next_gradient_preset_name(),
Some("") => return Err(bad(C, "the name is empty")),
Some(n) if s.gradient_preset(n).is_some() => return Err(bad(C, format!("a gradient preset is already called {n}"))),
Some(n) => n.to_string(),
};
s.prefs.gradient_presets.push(GradientPreset { name: name.clone(), gradient: unlinked(&g.gradient) });
Ok(json!({ "name": name }))
}
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "gradient.presets.delete";
let name = match text_param(p, "name", C)? {
Some(n) => n.trim().to_string(),
None => s
.active_saved_gradient_preset()
.map(str::to_string)
.ok_or_else(|| bad(C, "give a name, or paint the active proxy with a saved preset"))?,
};
if builtin_presets().any(|e| e.name.eq_ignore_ascii_case(&name)) {
return Err(bad(C, format!("{name} is built in and can't be deleted")));
}
let i = s
.prefs
.gradient_presets
.iter()
.position(|g| g.name.eq_ignore_ascii_case(&name))
.ok_or_else(|| bad(C, format!("no saved gradient preset called {name}")))?;
Ok(json!({ "deleted": s.prefs.gradient_presets.remove(i).name }))
}
+14 -219
View File
@@ -1,24 +1,16 @@
//! Object → Vector Halftone: the selected art (vectors, type, images) as vector dots, lines or
//! shapes sized by its tone.
//! shapes sized by its tone, as one undo step.
//!
//! The art is rendered offscreen and sampled 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; 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.
use std::sync::Arc;
//! The screens, dots and caps are Color Effects' Vector Halftone's
//! ([`vectorcraft_render::effects::addons::halftone`]), which draws the same dots live; the art is
//! sampled as [`vectorcraft_render::addons::halftone::sample`] draws it.
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
use vectorcraft_pathops as po;
use vectorcraft_pathops::BoolOp;
use vectorcraft_color::Color;
use vectorcraft_doc::Node;
use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes};
use super::edit::selected_roots;
use super::menucmds::isolated_doc;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, color_value, f64_or, has_selection, str_param};
pub fn specs() -> Vec<CommandSpec> {
@@ -33,102 +25,6 @@ pub fn specs() -> Vec<CommandSpec> {
)]
}
/// Most halftone cells per screen.
const MAX_CELLS: f64 = 100_000.0;
/// Most pixels the tone is sampled from.
const MAX_SAMPLE_PIXELS: f64 = 16.0e6;
/// Cells lighter than this get no dot.
const MIN_TONE: f64 = 0.01;
#[derive(Clone, Copy, Debug, PartialEq)]
enum DotShape {
Circle,
Ellipse,
Square,
Diamond,
Line,
}
impl DotShape {
fn parse(s: &str) -> Option<Self> {
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 (RGBA lightness for mono, CMYK inks for cmyk).
channel: usize,
}
/// The sampled art: `w`×`h` pixels of 4 bytes over `region` at `scale` px/pt.
struct Samples {
px: Vec<u8>,
w: usize,
h: usize,
region: Rect,
scale: f64,
/// Mono: tones are 1 − lightness of RGBA pixels; CMYK: ink amounts.
mono: bool,
invert: bool,
}
impl Samples {
/// The tone (0..1) of `channel` at document point `p`.
fn tone(&self, p: Point, channel: usize) -> f64 {
let x = ((p.x - self.region.x0) * self.scale).floor();
let y = ((p.y - self.region.y0) * self.scale).floor();
if !(x >= 0.0 && y >= 0.0 && (x as usize) < self.w && (y as usize) < self.h) {
return if self.invert { 1.0 } else { 0.0 };
}
let i = (y as usize * self.w + x as usize) * 4;
let byte = |k: usize| self.px.get(i + k).copied().unwrap_or(0) as f64 / 255.0;
let t = if self.mono { 1.0 - (0.2126 * byte(0) + 0.7152 * byte(1) + 0.0722 * byte(2)) } else { byte(channel) };
if self.invert { 1.0 - t } else { t }
}
/// 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 {
let mut sum = 0.0;
for i in 0..3 {
for j in 0..3 {
let off = Point::new((i as f64 - 1.0) * s / 3.0, (j as f64 - 1.0) * s / 3.0);
sum += self.tone(c + (rot * off).to_vec2(), channel);
}
}
sum / 9.0
}
}
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.vectorHalftone";
let shape = match str_param(p, "shape") {
@@ -153,7 +49,7 @@ fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
None => Color::BLACK,
};
let (invert, clip, keep) = (bool_or(p, "invert", false), bool_or(p, "clip", true), bool_or(p, "keepOriginal", false));
let cell = 72.0 / frequency;
let ht = Halftone { shape, frequency, angle, mono, color, from_art: false, invert, clip };
let roots = selected_roots(s)?;
let st = s.doc()?;
@@ -161,10 +57,7 @@ fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
if b.width() <= 0.0 || b.height() <= 0.0 || !b.area().is_finite() {
return Err(bad(C, "the selection has no area"));
}
// The grid turned by the screen angle covers at most (w + h)² / 2.
if (b.width() + b.height()).powi(2) / 2.0 / (cell * cell) > MAX_CELLS {
return Err(bad(C, "too many dots for this size: lower the frequency"));
}
let (region, scale) = ht.plan(b).ok_or_else(|| bad(C, "too many dots for this size: lower the frequency"))?;
let nodes: Vec<Node> = roots
.iter()
.filter_map(|id| st.doc.node(*id).cloned())
@@ -173,64 +66,18 @@ fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
n
})
.collect();
let outline = if clip {
vectorcraft_render::effects::clip_outline(&Node::group(NodeId(u64::MAX), nodes.iter().cloned().map(Arc::new).collect()))
} else {
None
};
// Sample the art at about four pixels per cell.
let scale = (4.0 / cell).min((MAX_SAMPLE_PIXELS / b.area()).sqrt()).clamp(0.01, 16.0);
let region = b.inflate(cell, cell);
let tmp = isolated_doc(&st.doc, nodes);
let mut r = vectorcraft_render::Renderer::new();
let (w, h) = vectorcraft_render::region_pixels(region, scale);
let (w, h) = (w as usize, h as usize);
let outline = if clip { art_outline(&nodes) } else { None };
let failed = vectorcraft_render::decode_failures();
let px = if mono {
r.render_region(&tmp, region, scale, true).pixels
} else {
r.render_region_inks(&tmp, region, scale, &vectorcraft_render::RenderOptions { skip_templates: true, ..Default::default() })
};
let samples = vectorcraft_render::addons::halftone::sample(&st.doc, nodes, region, scale, mono, invert);
let warning = super::rasterfx::undecoded_warning(failed);
if px.len() < w * h * 4 {
return Err(EngineError::Other("the art could not be sampled".into()));
}
let samples = Samples { px, w, h, region, scale, mono, invert };
let screens: Vec<Screen> = if mono {
vec![Screen { paint: color, angle, channel: 0 }]
} else {
// 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 },
]
};
let mut layers = vec![];
let mut dots = 0;
for sc in &screens {
let (path, n) = screen_dots(&samples, b, cell, sc, shape, outline.as_ref());
dots += n;
if !path.is_empty() {
layers.push((path, sc.paint));
}
}
let samples = samples.ok_or_else(|| EngineError::Other("the art could not be sampled".into()))?;
let (layers, dots) = ht.layers(&samples, b, outline.as_ref());
if layers.is_empty() {
return Err(EngineError::Other("the art is too light for any dots".into()));
}
let top = *roots.last().ok_or_else(|| bad(C, "nothing selected"))?;
let id = s.edit("Vector Halftone", |d, sel| {
let children = layers
.into_iter()
.map(|(path, ink)| {
let mut n = Node::path(d.alloc_id(), path, Appearance::basic(Paint::solid(ink), Paint::None, 0.0));
if !mono {
n.blend = BlendMode::Multiply;
}
Arc::new(n)
})
.collect();
let children = dot_nodes(layers, mono, &mut || d.alloc_id());
let gid = d.alloc_id();
let mut g = Node::group(gid, children);
g.name = Some("Vector Halftone".into());
@@ -249,55 +96,3 @@ fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(out)
}
/// The dots of one screen over `bounds` as one path, with their count.
fn screen_dots(samples: &Samples, bounds: Rect, cell: f64, sc: &Screen, shape: DotShape, outline: Option<&(BezPath, FillRule)>) -> (PathData, usize) {
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 inside, mut edge) = (vec![], 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;
let dot = shape.path(t, cell).transformed(place);
// Dots wholly inside the outline need no clipping.
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 count = inside.len() + edge.len();
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), count)
}
Loaded 100 of 431 files, more files were not shown because too many files have changed in this diff. Show more