mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-22 02:15:24 +01:00
Merge main into fix/placed-gradient-follows-warp
This commit is contained in:
commit
c63f634e0c
603 files changed
+67398
-2766
No files matched your search
@@ -1,2 +1,9 @@
|
||||
[alias]
|
||||
xtask = "run --package xtask --"
|
||||
|
||||
# WebAssembly SIMD for the web build: without it vello_cpu's SIMD layer (fearless_simd) runs its
|
||||
# scalar fallback on wasm32 and the canvas renders about 2.4x slower (#2786). The web build then
|
||||
# needs Chrome/Edge 91+, Firefox 89+ or Safari 16.4+. A RUSTFLAGS environment variable replaces
|
||||
# these flags.
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = ["-C", "target-feature=+simd128"]
|
||||
@@ -368,6 +368,18 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` |
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` |
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 red, green, blue and white quadrants encoded with libheif's `heif-enc` 1.23.2 (x265); SHA-256 `122d14963fe899daa736cd216902cf4fc8f2192b3a0ba81f94004adcd71a0ff5` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-alpha.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with a transparent right half, encoded with `heif-enc` 1.23.2; SHA-256 `55b5a537401ead742714c3a1bc526559ec8c1ba97cdb7f43ac63f4037167475b` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-10bit.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants at 10 bits, encoded with `heif-enc` 1.23.2; SHA-256 `11014848c6a838e5799d87e034eff1b06b816712ed70ba451bd582d72741774f` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-grid.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 128 × 128 quadrants as a 2 × 2 grid of 64 × 64 tiles, encoded with `heif-enc` 1.23.2; SHA-256 `5802f8715110954eb9c58d4bdcc10d1200426a48cf726f1b88dfb60da825ba7a` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-300ppi.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with EXIF resolution tags of 300 ppi, encoded with `heif-enc` 1.23.2; SHA-256 `6a344a6de04fc5fceaee46b6e0028b12478c90bdcb6f6f14ed8c86a44cb203d7` |
|
||||
| `crates/engine/tests/fixtures/heif/wide-rotated.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 16 red and blue halves stored with a quarter-turn rotation, encoded with `heif-enc` 1.23.2; SHA-256 `e3a2c3a9beb4066c13d6deb8e1311805c6aac485fde8784f1ee317dd95b89973` |
|
||||
| `crates/engine/tests/fixtures/heif/wide-rotated-300x150.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the rotated halves with EXIF resolution tags of 300 ppi across and 150 ppi down, encoded with `heif-enc` 1.23.2; SHA-256 `79ad7945cd2c1ea9d3e70ac9b93d9a162fd8ce37541a0f3de44e12f04745921d` |
|
||||
| `crates/engine/tests/fixtures/heif/tones.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants of four mid tones, encoded with `heif-enc` 1.23.2; SHA-256 `29ed7d75fbfbc4c298eb2da3a6b62625a150cd6bfe5b7ff1d847437501b1b4b1` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-nclx.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones labeled Display P3 in an `nclx` color box, encoded with `heif-enc` 1.23.2; SHA-256 `baeb32ffa58ac1ac29a00c9e388b9281f4acb4695c4681e4933d0ad061447101` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-icc.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile (`vectorcraft_color::cms::icc_bytes`), encoded with `heif-enc` 1.23.2; SHA-256 `472e1a123b9515926a8985a04c3f680387e8c410dbf8f7ff0cfb8cb99c89e93b` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-icc-only.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile as their only color box, encoded with `heif-enc` 1.23.2; SHA-256 `2654fdd21e56641107db20b3f4d0a66a86420ac040d42ddf55e20f7e789d5c55` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-grid16.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each cropped from a 64 × 64 picture, encoded with `heif-enc` 1.23.2; SHA-256 `bd114ee66cdac10142729dc9dddfa1cd96993a5cefa54c2f25b65496652f007f` |
|
||||
|
||||
## Assets embedded by the PDF backend
|
||||
|
||||
|
||||
Generated
+64
-6
@@ -1442,7 +1442,7 @@ dependencies = [
|
||||
"itertools",
|
||||
"log",
|
||||
"profiling",
|
||||
"resvg",
|
||||
"resvg 0.45.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2286,6 +2286,15 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "heic-rs"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8883c3bfa6b4ff19a40e52a6dc051c5612cbe21bf408fc6d4875e8dfd777cb66"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
@@ -2978,8 +2987,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=481f66d287b2a06845f3667a19daf35f0fe958ed#481f66d287b2a06845f3667a19daf35f0fe958ed"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4430,11 +4438,29 @@ dependencies = [
|
||||
"pico-args",
|
||||
"rgb",
|
||||
"svgtypes 0.15.3",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.11.4",
|
||||
"usvg 0.45.1",
|
||||
"zune-jpeg 0.4.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "resvg"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"gif 0.14.2",
|
||||
"image-webp",
|
||||
"log",
|
||||
"pico-args",
|
||||
"rgb",
|
||||
"svgtypes 0.16.1",
|
||||
"tiny-skia 0.12.0",
|
||||
"usvg 0.48.1",
|
||||
"zune-jpeg 0.5.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfd"
|
||||
version = "0.17.2"
|
||||
@@ -4719,7 +4745,7 @@ checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
|
||||
dependencies = [
|
||||
"log",
|
||||
"smithay-client-toolkit 0.19.2",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5585,6 +5611,21 @@ dependencies = [
|
||||
"tiny-skia-path 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-skia"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
|
||||
dependencies = [
|
||||
"arrayref",
|
||||
"arrayvec",
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"tiny-skia-path 0.12.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny-skia-path"
|
||||
version = "0.11.4"
|
||||
@@ -6227,7 +6268,9 @@ version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"resvg 0.48.1",
|
||||
"serde_json",
|
||||
"svgtypes 0.16.1",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom",
|
||||
@@ -6247,10 +6290,12 @@ dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-jpeg2000",
|
||||
"heic-rs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.6",
|
||||
"ruzstd",
|
||||
@@ -6265,6 +6310,7 @@ dependencies = [
|
||||
"vectorcraft-eps",
|
||||
"vectorcraft-format",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-js",
|
||||
"vectorcraft-metafile",
|
||||
"vectorcraft-pathops",
|
||||
"vectorcraft-pdf",
|
||||
@@ -6283,6 +6329,7 @@ dependencies = [
|
||||
name = "vectorcraft-eps"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"fax",
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -6291,6 +6338,7 @@ dependencies = [
|
||||
"memchr",
|
||||
"ruzstd",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
@@ -6332,6 +6380,14 @@ dependencies = [
|
||||
"vectorcraft-testkit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-js"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"unicode-general-category",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.21.0"
|
||||
@@ -6413,8 +6469,10 @@ dependencies = [
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
@@ -6469,7 +6527,7 @@ dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
"resvg",
|
||||
"resvg 0.45.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"simplecss",
|
||||
|
||||
@@ -53,6 +53,7 @@ vectorcraft-metafile = { path = "crates/metafile" }
|
||||
vectorcraft-plugins = { path = "crates/plugins" }
|
||||
vectorcraft-affinity = { path = "crates/affinity" }
|
||||
vectorcraft-scriptcheck = { path = "crates/scriptcheck" }
|
||||
vectorcraft-js = { path = "crates/js" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -153,6 +154,7 @@ hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -20,10 +20,15 @@ list (author, source, license) is in ASSETS.md.
|
||||
(Ubuntu Font Licence 1.0), Hack (MIT), Noto Emoji (SIL Open Font License 1.1) and emoji-icon-font
|
||||
(MIT). Their license texts ship with that crate.
|
||||
|
||||
Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, linesweeper, egui, eframe, …) are
|
||||
Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, egui, eframe, …) are
|
||||
fetched through crates.io under their own permissive licenses (mostly MIT and/or Apache-2.0; also
|
||||
BSD, ISC, Zlib, BSL-1.0 and Unicode-3.0).
|
||||
|
||||
linesweeper 0.5.0 (MIT OR Apache-2.0) is fetched from https://github.com/storytold/craft-libs at
|
||||
revision 481f66d287b2a06845f3667a19daf35f0fe958ed. The copy in craft-libs' vendor/linesweeper is
|
||||
the crates.io package with no file changed, and it keeps the package's LICENSE-MIT and
|
||||
LICENSE-APACHE.
|
||||
|
||||
JPEG export uses the jpeg-encoder crate (MIT OR Apache-2.0, and the IJG License): this software is
|
||||
based in part on the work of the Independent JPEG Group.
|
||||
|
||||
|
||||
@@ -253,7 +253,7 @@ The scores are self-assessed from our code against public documentation;
|
||||
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
|
||||
|
||||
**What's missing:**
|
||||
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes leaves out live effects and writes symbols and live objects as their art);
|
||||
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
|
||||
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
|
||||
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
|
||||
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
|
||||
@@ -317,7 +317,7 @@ Installers and executables are code-signed.
|
||||
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| Static site | `vectorcraft-web-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
| Static site | `vectorcraft-web-<ver>.zip` | Runs in a browser with WebAssembly SIMD (Chrome/Edge 91, Firefox 89, Safari 16.4 or newer), see `packaging/web/README.md`; host it on any static server |
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
|
||||
+5
-2
@@ -14,7 +14,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-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates 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
|
||||
@@ -24,7 +24,7 @@ and the work list in [`docs/gaps.md`](docs/gaps.md).
|
||||
**Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance,
|
||||
type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's
|
||||
own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that
|
||||
leaves out live effects and writes symbols and live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
|
||||
keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
|
||||
app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow
|
||||
gate: all six core workflows (path drawing and editing, paint and style, type, layers/artboards/export, print
|
||||
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
|
||||
@@ -34,6 +34,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
|
||||
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
|
||||
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
|
||||
@@ -134,6 +135,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
@@ -223,6 +225,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
|
||||
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
|
||||
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
|
||||
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
|
||||
|
||||
@@ -16,7 +16,7 @@ workspace = true
|
||||
[dependencies]
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-format = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-svg = { workspace = true }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `vectorcraft-cli`: VectorCraft from the command line.
|
||||
//!
|
||||
//! ```text
|
||||
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
|
||||
//! vectorcraft-cli commands
|
||||
@@ -72,6 +73,11 @@ const USAGE: &str = "\
|
||||
vectorcraft-cli — VectorCraft automation
|
||||
|
||||
USAGE:
|
||||
vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
Run any subcommand without plug-ins: none loads or runs, and plug-in commands report that
|
||||
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
|
||||
does not take --connect.
|
||||
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
|
||||
(vectorcraft --control 7979), falling back to a headless in-process session.
|
||||
@@ -128,12 +134,17 @@ USAGE:
|
||||
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
|
||||
(warm), multithreaded and single-threaded.
|
||||
|
||||
vectorcraft-cli perf [--paths N] [--deep]
|
||||
vectorcraft-cli perf [--paths N] [--deep] [--native-io [--artboards 1..4]]
|
||||
Check the performance budgets (render, pan, hit test, save/load, SVG, Pathfinder, handle
|
||||
and segment drags) on a synthetic N-path document (default 50000). Exits non-zero if a
|
||||
budget is exceeded, unless the report says the machine is busy. --deep also times work with
|
||||
no budget yet and prints memory use (the working set on Windows), with the peak so far on
|
||||
Windows and Linux.
|
||||
--native-io instead measures the application's native save/open commands (one warmup,
|
||||
five samples, no disk I/O), including preview, PDF, compression and API base64 costs.
|
||||
It reports the default and explicit PDF opt-out, with and without preview/compression;
|
||||
--artboards repeats the same artwork
|
||||
on 1 to 4 overlapping artboards. This mode allows at most 50000 paths.
|
||||
";
|
||||
|
||||
/// The usage text plus the formats `document.open` reads and `document.export` writes.
|
||||
@@ -175,12 +186,18 @@ fn main() -> ExitCode {
|
||||
#[cfg(target_os = "macos")]
|
||||
mac_fonts::install();
|
||||
prefs_dir::install_fonts();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// Before any subcommand attaches the plug-in folder.
|
||||
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
|
||||
if safe_mode {
|
||||
args.remove(0);
|
||||
vectorcraft_engine::cmd::plugin::start_in_safe_mode();
|
||||
}
|
||||
let r = match args.first().map(String::as_str) {
|
||||
// `commands` and `info` take no options, so `--help` or `-h` anywhere after them prints the
|
||||
// usage. The other subcommands check for it themselves.
|
||||
Some("commands" | "info") if help_requested(&args[1..], &[]) => help(),
|
||||
Some("mcp") => mcp(&args[1..]),
|
||||
Some("mcp") => mcp(&args[1..], safe_mode),
|
||||
Some("run") => run(&args[1..]),
|
||||
Some("commands") => commands(),
|
||||
Some("convert") => convert(&args[1..]),
|
||||
@@ -213,7 +230,9 @@ fn with_stores(mut h: Headless) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
fn mcp(args: &[String]) -> Result<(), String> {
|
||||
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
|
||||
/// plug-ins, so `--connect` is refused and the default does not connect.
|
||||
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
|
||||
return help();
|
||||
}
|
||||
@@ -240,6 +259,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
if headless && connect.is_some() {
|
||||
return Err("use either --connect or --headless".into());
|
||||
}
|
||||
if safe_mode && connect.is_some() {
|
||||
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
|
||||
}
|
||||
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
|
||||
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?;
|
||||
@@ -252,7 +274,7 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
file_access::confine_process(roots.clone());
|
||||
eprintln!("vectorcraft-cli: files confined: {}", roots.describe());
|
||||
Box::new(Headless::with_document().with_automation_roots(Some(roots)))
|
||||
} else if headless {
|
||||
} else if headless || safe_mode {
|
||||
Box::new(with_stores(Headless::with_document()))
|
||||
} else if let Some(addr) = connect {
|
||||
// Explicit address: fail loudly if the app isn't there.
|
||||
|
||||
@@ -64,6 +64,61 @@ fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 {
|
||||
v.get(v.len() / 2).copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Exercise the application's native save/open commands, including previews, PDF output,
|
||||
/// compression and API base64 conversion. Session setup and validation are outside timing.
|
||||
/// Five measured runs follow one warmup; no filesystem or GPU window is involved.
|
||||
fn native_io(doc: &Document) -> Result<(), String> {
|
||||
for (label, compatible, preview) in [
|
||||
("default options", None, false),
|
||||
("PDF disabled", Some(false), false),
|
||||
("preview+gzip", None, true),
|
||||
("preview+gzip, PDF disabled", Some(false), true),
|
||||
] {
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.add_document(doc.clone(), None);
|
||||
let mut params = json!({"format":"vectorcraft","modified":null,"preview":preview,"compress":preview});
|
||||
if let Some(value) = compatible {
|
||||
params["pdfCompatible"] = json!(value);
|
||||
}
|
||||
let (mut saves, mut opens) = (Vec::new(), Vec::new());
|
||||
let (mut size, mut has_pdf, mut compressed) = (0, false, false);
|
||||
for run in 0..6 {
|
||||
let start = Instant::now();
|
||||
let saved = session.execute("file.saveAs", ¶ms).map_err(|e| e.to_string())?;
|
||||
let save_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let data = saved["dataBase64"].as_str().ok_or("native save returned no dataBase64")?;
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or("native save returned invalid base64")?;
|
||||
size = bytes.len();
|
||||
has_pdf = vectorcraft_format::pdf_content(&bytes).is_some();
|
||||
if compatible == Some(false) && has_pdf {
|
||||
return Err("native save ignored the explicit PDF opt-out".into());
|
||||
}
|
||||
compressed = vectorcraft_format::is_compressed(&bytes);
|
||||
if compressed != preview || vectorcraft_format::preview(&bytes).is_some() != preview {
|
||||
return Err("native save did not apply the requested preview/compression options".into());
|
||||
}
|
||||
let args = json!({"name":"perf.vectorcraft","dataBase64":data});
|
||||
let mut opened = vectorcraft_engine::Session::new();
|
||||
let start = Instant::now();
|
||||
opened.execute("document.open", &args).map_err(|e| e.to_string())?;
|
||||
let open_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
if opened.doc().map_err(|e| e.to_string())?.doc.artboards.len() != doc.artboards.len() {
|
||||
return Err("native round trip changed the artboard count".into());
|
||||
}
|
||||
if run > 0 {
|
||||
saves.push(save_ms);
|
||||
opens.push(open_ms);
|
||||
}
|
||||
}
|
||||
saves.sort_by(f64::total_cmp);
|
||||
opens.sort_by(f64::total_cmp);
|
||||
let save = saves.get(2).copied().ok_or("no save measurements")?;
|
||||
let open = opens.get(2).copied().ok_or("no open measurements")?;
|
||||
outln!(" native {label}: save {save:.2} ms, open {open:.2} ms, {size} bytes, PDF {has_pdf}, compressed {compressed}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 1-minute load average (macOS / Linux), if available.
|
||||
#[cfg(not(windows))]
|
||||
fn load_average() -> Option<f64> {
|
||||
@@ -393,19 +448,36 @@ fn deep(n: usize) -> Result<(), String> {
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
if crate::help_requested(args, &["--paths"]) {
|
||||
if crate::help_requested(args, &["--paths", "--artboards"]) {
|
||||
return crate::help();
|
||||
}
|
||||
let mut n = 50_000usize;
|
||||
let mut want_deep = false;
|
||||
let mut want_native = false;
|
||||
let mut artboards = None::<usize>;
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--deep" => want_deep = true,
|
||||
"--native-io" => want_native = true,
|
||||
"--artboards" => {
|
||||
artboards =
|
||||
Some(it.next().and_then(|v| v.parse().ok()).filter(|n| (1..=4).contains(n)).ok_or("--artboards needs a number from 1 to 4")?)
|
||||
}
|
||||
"--paths" => n = it.next().and_then(|v| v.parse().ok()).ok_or("--paths needs a number")?,
|
||||
other => return Err(format!("unknown perf option `{other}`")),
|
||||
}
|
||||
}
|
||||
if want_native && n > 50_000 {
|
||||
return Err("--native-io allows at most 50000 paths".into());
|
||||
}
|
||||
if want_native && want_deep {
|
||||
return Err("--native-io and --deep are separate measurement modes".into());
|
||||
}
|
||||
if artboards.is_some() && !want_native {
|
||||
return Err("--artboards requires --native-io".into());
|
||||
}
|
||||
let artboards = artboards.unwrap_or(1);
|
||||
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
|
||||
// The figure is the 1-minute load average, or on Windows the cores busy over one second.
|
||||
#[cfg(not(windows))]
|
||||
@@ -418,8 +490,20 @@ pub fn run(args: &[String]) -> Result<(), String> {
|
||||
outln!("WARNING: the machine is busy; wall-clock timings below are not trustworthy.");
|
||||
}
|
||||
let t = Instant::now();
|
||||
let doc = synthetic(n)?;
|
||||
let mut doc = synthetic(n)?;
|
||||
outln!(" (built in {:.0} ms)", t.elapsed().as_secs_f64() * 1000.0);
|
||||
if want_native {
|
||||
let first = doc.artboards.first().cloned().ok_or("synthetic document has no artboard")?;
|
||||
// Overlapping artboards intentionally repeat the same paths on every PDF page.
|
||||
for index in 1..artboards {
|
||||
let mut page = first.clone();
|
||||
page.id = first.id.checked_add(index as u32).ok_or("artboard id overflow")?;
|
||||
page.name = format!("Perf {}", index + 1);
|
||||
doc.artboards.push(page);
|
||||
}
|
||||
outln!(" application native I/O: {artboards} overlapping artboard(s), one warmup + five samples; medians; no disk I/O");
|
||||
return native_io(&doc);
|
||||
}
|
||||
|
||||
let mut rows: Vec<(&str, f64, f64)> = vec![];
|
||||
let opts = RenderOptions::default();
|
||||
@@ -513,6 +597,24 @@ pub fn run(args: &[String]) -> Result<(), String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_io_exercises_the_application_save_and_open_commands() {
|
||||
native_io(&synthetic(3).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_io_rejects_conflicting_modes_and_excessive_workloads() {
|
||||
for (args, expected) in [
|
||||
(vec!["--native-io", "--deep"], "separate measurement modes"),
|
||||
(vec!["--native-io", "--paths", "50001"], "at most 50000"),
|
||||
(vec!["--native-io", "--artboards", "5"], "1 to 4"),
|
||||
(vec!["--artboards", "1"], "requires --native-io"),
|
||||
(vec!["--artboards", "2"], "requires --native-io"),
|
||||
] {
|
||||
assert!(run(&args.into_iter().map(str::to_owned).collect::<Vec<_>>()).unwrap_err().contains(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_share_leaves_out_idle_time() {
|
||||
// In one second four processors log 40,000,000 ticks of 100 ns of kernel and user time,
|
||||
|
||||
@@ -283,6 +283,22 @@ fn mcp_headless_over_stdio() {
|
||||
assert_eq!(replies[3]["result"]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
/// `--safe-mode mcp` serves a headless session without plug-ins: it refuses `--connect`, and by
|
||||
/// default it does not connect to an app listening on the default address, which loads its own
|
||||
/// plug-ins.
|
||||
#[test]
|
||||
fn safe_mode_mcp_does_not_connect_to_a_running_app() {
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}");
|
||||
// Something listening on the default address, as a running app does; a running app or another
|
||||
// program already holding it serves as well.
|
||||
let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR);
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}");
|
||||
}
|
||||
|
||||
/// `mcp --automation-read-root` / `--automation-write-root` (#832): the flags are checked before the
|
||||
/// server starts, and the process then reads and writes only inside its roots.
|
||||
#[test]
|
||||
|
||||
@@ -14,7 +14,7 @@ name = "vectorcraft-web"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
|
||||
@@ -15,7 +15,7 @@ wgpu = ["eframe/wgpu", "dep:winsafe"]
|
||||
accessibility = ["eframe/accesskit"]
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app)
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::windows_stylus;
|
||||
use super::{App, VectorcraftApp, file_access, window};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_menu, mac_window, open_documents};
|
||||
use vectorcraft_ui_egui::dialogs::safe_mode;
|
||||
|
||||
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
|
||||
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
|
||||
@@ -113,16 +114,26 @@ impl App {
|
||||
vectorcraft_ui_egui::background::wait_all(&mut self.app);
|
||||
return;
|
||||
}
|
||||
// An app that stays in Safe Mode leaves later launches to start their own app with plug-ins.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if safe_mode::staying_on(&self.app) {
|
||||
single_instance::resign();
|
||||
}
|
||||
// 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() {
|
||||
// dialog is open: what asked for it runs again on its document when it answers. They also
|
||||
// wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as
|
||||
// do the command line's files held back for it. Files later launches handed over before the
|
||||
// choice ended in Safe Mode open in a new app with plug-ins.
|
||||
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) {
|
||||
let held = std::mem::take(&mut self.held_files);
|
||||
#[cfg(target_os = "macos")]
|
||||
let files = open_documents::take();
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let files = single_instance::take();
|
||||
let files = single_instance::take_for_frame(safe_mode::staying_on(&self.app), single_instance::launch_with_plug_ins);
|
||||
if !files.is_empty() {
|
||||
bring_window_forward(ctx);
|
||||
}
|
||||
open_files(&mut self.app, held);
|
||||
open_files(&mut self.app, files);
|
||||
}
|
||||
let (now, zoom) = (ctx.input(|i| i.time), ctx.zoom_factor());
|
||||
@@ -151,13 +162,15 @@ impl App {
|
||||
/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting,
|
||||
/// before eframe tears the window down (#661). AccessKit then gives the window's content view back
|
||||
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
|
||||
/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit.
|
||||
/// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed
|
||||
/// after the window, so it is ended here as `main` ends it after the window on other platforms.
|
||||
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
|
||||
/// failure then starts the app again on another adapter (#651).
|
||||
#[allow(unused_variables)]
|
||||
fn end_before_teardown(frames: u64) {
|
||||
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
|
||||
if frames >= gpu::STARTUP_FRAMES {
|
||||
safe_mode::end_launch();
|
||||
log::info!("quitting");
|
||||
log::logger().flush();
|
||||
std::process::exit(0);
|
||||
@@ -172,6 +185,16 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
}
|
||||
|
||||
/// Open the command line's `files` now, or, while the choice about a stopped plug-in is up
|
||||
/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads.
|
||||
pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec<String>) -> Vec<String> {
|
||||
if safe_mode::choosing(app) {
|
||||
return files;
|
||||
}
|
||||
open_files(app, files);
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// 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>) {
|
||||
|
||||
@@ -310,7 +310,7 @@ fn pci_ids(device_id: &str) -> Option<(u32, u32)> {
|
||||
let field = |key: &str| {
|
||||
device_id.split(['\\', '&']).find_map(|part| {
|
||||
let (name, hex) = part.split_at_checked(key.len())?;
|
||||
if name.eq_ignore_ascii_case(key) { u32::from_str_radix(hex, 16).ok() } else { None }
|
||||
if name.eq_ignore_ascii_case(key) && hex.bytes().all(|b| b.is_ascii_hexdigit()) { u32::from_str_radix(hex, 16).ok() } else { None }
|
||||
})
|
||||
};
|
||||
Some((field("VEN_")?, field("DEV_")?))
|
||||
|
||||
@@ -820,3 +820,10 @@ fn crashes_are_forgotten_in_another_version_or_under_another_preference() {
|
||||
assert_eq!(record.crashed.len(), CRASHED_LIMIT);
|
||||
assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013"));
|
||||
}
|
||||
|
||||
/// `u32::from_str_radix` accepts a leading `+`; a device id with one is not a PCI id.
|
||||
#[test]
|
||||
fn pci_ids_reject_a_sign_in_the_hex_digits() {
|
||||
assert_eq!(pci_ids("PCI\\VEN_+10DE&DEV_2204"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_+2204"), None);
|
||||
}
|
||||
+107
-39
@@ -1,7 +1,10 @@
|
||||
//! VectorCraft desktop app.
|
||||
//!
|
||||
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
|
||||
//! [--in-window-menus] [--new-instance] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//!
|
||||
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
|
||||
//! a file.
|
||||
//!
|
||||
//! Files given while VectorCraft already runs open in that window, unless `--new-instance` is given
|
||||
//! (Windows and Linux; `single_instance`).
|
||||
@@ -65,6 +68,7 @@ mod xwayland;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
use vectorcraft_ui_egui::dialogs::safe_mode;
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
use vectorcraft_ui_egui::picks::PickRequest;
|
||||
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
|
||||
@@ -77,7 +81,7 @@ mod titlebar;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use app::bring_window_forward;
|
||||
use app::native_input_hook;
|
||||
use app::open_files;
|
||||
use app::open_or_hold;
|
||||
use host_services::services;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
|
||||
@@ -92,7 +96,9 @@ use titlebar::custom_titlebar_from;
|
||||
use titlebar::opted_into_system_title_bar;
|
||||
#[cfg(windows)]
|
||||
use titlebar::set_taskbar_icon;
|
||||
use titlebar::{custom_titlebar, native_options};
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame};
|
||||
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
|
||||
|
||||
struct App {
|
||||
app: VectorcraftApp,
|
||||
@@ -111,6 +117,8 @@ struct App {
|
||||
pending_maximize: bool,
|
||||
/// Frames left to retry [`window::apply_pending_maximize`].
|
||||
maximize_tries: u8,
|
||||
/// The command line's files, held back until the choice about a stopped plug-in is made.
|
||||
held_files: Vec<String>,
|
||||
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
|
||||
monitors_listed: Option<(f64, f32)>,
|
||||
}
|
||||
@@ -132,13 +140,89 @@ Options:
|
||||
(or VECTORCRAFT_IN_WINDOW_MENUS=1)
|
||||
--new-instance Open the files in a new window even when VectorCraft
|
||||
already runs (Windows and Linux)
|
||||
--safe-mode Start without plug-ins: none loads or runs until
|
||||
VectorCraft starts normally (Help › Safe Mode); the
|
||||
files open in a new window, as with --new-instance
|
||||
--version Print the version and exit
|
||||
-h, --help Print this help and exit
|
||||
-- Treat every argument after it as a file
|
||||
|
||||
Any other argument starting with '-' is an error.
|
||||
|
||||
Without a window (converting, scripting, the MCP server), use vectorcraft-cli:
|
||||
vectorcraft-cli --help
|
||||
";
|
||||
|
||||
/// The command line's options other than the automation roots and the control port.
|
||||
struct CommandLine {
|
||||
files: Vec<String>,
|
||||
in_window_menus: bool,
|
||||
new_instance: bool,
|
||||
/// `--safe-mode`: no plug-in loads or runs in this launch.
|
||||
safe_mode: bool,
|
||||
}
|
||||
|
||||
/// Reads the arguments after the program name. The automation roots and the control port go into
|
||||
/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and
|
||||
/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails.
|
||||
fn read_command_line(
|
||||
mut args: impl Iterator<Item = String>,
|
||||
control: &mut automation_args::ControlArg,
|
||||
roots_args: &mut automation_args::AutomationArgs,
|
||||
) -> Result<CommandLine, std::process::ExitCode> {
|
||||
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 safe_mode = false;
|
||||
let mut unknown = None;
|
||||
while let Some(a) = args.next() {
|
||||
// After `--`, every argument is a file, even one whose name starts with '-'.
|
||||
if a == "--" {
|
||||
files.extend(args.by_ref());
|
||||
break;
|
||||
}
|
||||
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
match a.as_str() {
|
||||
"--in-window-menus" => in_window_menus = true,
|
||||
"--new-instance" => new_instance = true,
|
||||
"--safe-mode" => safe_mode = true,
|
||||
"--version" => {
|
||||
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Err(std::process::ExitCode::SUCCESS);
|
||||
}
|
||||
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
|
||||
// used to open (or hang without a display) instead (#2110).
|
||||
"--help" | "-h" => {
|
||||
// Not `print!`, which panics when standard output is closed (`| head -0`):
|
||||
// there is nothing left to tell then.
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return Err(std::process::ExitCode::SUCCESS);
|
||||
}
|
||||
// The process serial number older macOS versions pass to an app the Finder starts.
|
||||
#[cfg(target_os = "macos")]
|
||||
_ if a.starts_with("-psn_") => {}
|
||||
// An option this version doesn't know (a typo such as `--safe-mod`) is an error, not a
|
||||
// file to open. Reported after the loop, so a later `--help` or `--version` still wins.
|
||||
_ if a.starts_with('-') && a != "-" => {
|
||||
unknown.get_or_insert(a);
|
||||
}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
if let Some(a) = unknown {
|
||||
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
|
||||
}
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
@@ -154,37 +238,11 @@ fn main() -> std::process::ExitCode {
|
||||
let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
|
||||
let mut roots_args =
|
||||
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) }) {
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return std::process::ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
|
||||
// used to open (or hang without a display) instead (#2110).
|
||||
"--help" | "-h" => {
|
||||
// Not `print!`, which panics when standard output is closed (`| head -0`):
|
||||
// there is nothing left to tell then.
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return std::process::ExitCode::SUCCESS;
|
||||
}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) {
|
||||
Ok(command_line) => command_line,
|
||||
Err(code) => return code,
|
||||
};
|
||||
let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args;
|
||||
// After the arguments: `--control` and `--version` win over a bad environment value.
|
||||
let control_port = match control.port {
|
||||
@@ -202,10 +260,10 @@ fn main() -> std::process::ExitCode {
|
||||
// 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) {
|
||||
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
|
||||
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
|
||||
single_instance::Start::Running(primary) => primary,
|
||||
};
|
||||
single_instance::Start::Running(primary) => single_instance::hold(primary),
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ = new_instance;
|
||||
vectorcraft_ui_egui::i18n::detect_system_lang_in_background();
|
||||
@@ -396,10 +454,15 @@ fn main() -> std::process::ExitCode {
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
// Before any plug-in loads: this launch's marker in the Launch folder next to the
|
||||
// preferences (none for runs without preferences), and Safe Mode.
|
||||
let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch")));
|
||||
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
|
||||
// which takes over from the copy the preferences file used to hold.
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
@@ -466,7 +529,9 @@ fn main() -> std::process::ExitCode {
|
||||
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
|
||||
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
|
||||
}
|
||||
app.titlebar_from_env = titlebar_from_env();
|
||||
app.custom_titlebar = custom_titlebar;
|
||||
app.desktop_frame = !custom_titlebar;
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx).with_automation_roots(roots.clone());
|
||||
@@ -491,7 +556,7 @@ fn main() -> std::process::ExitCode {
|
||||
single_instance::set_ui(&cc.egui_ctx);
|
||||
}
|
||||
app.services.native_input_hook = native_input_hook(&app);
|
||||
file_access::unconfined(|| open_files(&mut app, files));
|
||||
let held_files = file_access::unconfined(|| open_or_hold(&mut app, files));
|
||||
// The first frame is due from now (`gpu::watch_first_frame`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
created.ready();
|
||||
@@ -507,6 +572,7 @@ fn main() -> std::process::ExitCode {
|
||||
winit_window,
|
||||
pending_maximize,
|
||||
maximize_tries: 8,
|
||||
held_files,
|
||||
monitors_listed: None,
|
||||
}))
|
||||
}),
|
||||
@@ -515,7 +581,9 @@ 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);
|
||||
single_instance::resign();
|
||||
// The process ends normally from here: this launch didn't stop while a plug-in was loading.
|
||||
safe_mode::end_launch();
|
||||
#[cfg(feature = "wgpu")]
|
||||
let outcome = gpu::finish(outcome, &startup);
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
|
||||
@@ -12,8 +12,12 @@
|
||||
//! 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.
|
||||
//! nor listen, and neither does a `--safe-mode` launch, which opens its files in an app of its own
|
||||
//! and leaves later launches to start theirs with plug-ins. `--new-instance` opens a launch's files
|
||||
//! in an app of its own. An app that stays in Safe Mode after the choice about a stopped plug-in
|
||||
//! stops listening ([`resign`]), and files later launches handed it before then open in a new app
|
||||
//! with plug-ins ([`take_for_frame`]). 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};
|
||||
@@ -43,6 +47,8 @@ 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());
|
||||
/// This app while it is the one later launches hand their files to ([`hold`]).
|
||||
static HELD: Mutex<Option<Primary>> = Mutex::new(None);
|
||||
/// The UI to wake when files arrive (unset until the window exists; the first frame opens them).
|
||||
static UI: OnceLock<egui::Context> = OnceLock::new();
|
||||
|
||||
@@ -56,23 +62,46 @@ pub enum Start {
|
||||
|
||||
/// 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 {
|
||||
pub fn start(automation: bool, new_instance: bool, safe_mode: 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) };
|
||||
start_at(&path, new_instance, safe_mode, files)
|
||||
}
|
||||
|
||||
/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps
|
||||
/// its files and runs as its own app: a running app would open them with its plug-ins loaded. A
|
||||
/// `--safe-mode` launch never becomes the app later launches hand their files to, which would open
|
||||
/// them without plug-ins.
|
||||
fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
if safe_mode {
|
||||
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) {
|
||||
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))
|
||||
Start::Running(listen(path, queue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `primary` ([`start`]'s) until [`resign`].
|
||||
pub fn hold(primary: Option<Primary>) {
|
||||
*HELD.lock().unwrap_or_else(PoisonError::into_inner) = primary;
|
||||
}
|
||||
|
||||
/// Later launches start their own app from now on: the endpoint file goes. The app calls it when
|
||||
/// its window is gone, and when it stays in Safe Mode after the choice about a stopped plug-in.
|
||||
pub fn resign() {
|
||||
let primary = HELD.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
drop(primary);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -84,6 +113,43 @@ pub fn take() -> Vec<String> {
|
||||
std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner))
|
||||
}
|
||||
|
||||
/// The paths later launches handed over since the last call, to open in this app. An app that
|
||||
/// stays in Safe Mode (`safe_mode`) resigns and hands them to a new app with plug-ins (`launch`,
|
||||
/// [`launch_with_plug_ins`] in the app) instead: they arrived while it was the primary, before the
|
||||
/// choice about a stopped plug-in ended in Safe Mode, or just before it resigned. When `launch`
|
||||
/// fails (logged), they open here.
|
||||
pub fn take_for_frame(safe_mode: bool, launch: impl FnOnce(&[String]) -> io::Result<()>) -> Vec<String> {
|
||||
let files = take();
|
||||
if !safe_mode {
|
||||
return files;
|
||||
}
|
||||
// First, so the new app becomes the primary instead of handing the files back.
|
||||
resign();
|
||||
if files.is_empty() {
|
||||
return files;
|
||||
}
|
||||
match launch(&files) {
|
||||
Ok(()) => Vec::new(),
|
||||
Err(e) => {
|
||||
log::warn!("couldn't start VectorCraft with plug-ins for the files another launch opened: {e}");
|
||||
files
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start this program again, with plug-ins, on `files`.
|
||||
pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
|
||||
app_with_plug_ins(&std::env::current_exe()?, files).spawn().map(drop)
|
||||
}
|
||||
|
||||
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
|
||||
/// stays a file.
|
||||
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
|
||||
let mut command = std::process::Command::new(exe);
|
||||
command.arg("--").args(files);
|
||||
command
|
||||
}
|
||||
|
||||
fn queue(files: Vec<String>) {
|
||||
PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(files);
|
||||
if let Some(ctx) = UI.get() {
|
||||
@@ -263,6 +329,13 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Held by the tests that use the process-wide [`HELD`] and [`PENDING`], one at a time.
|
||||
static GLOBALS: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn globals() -> std::sync::MutexGuard<'static, ()> {
|
||||
GLOBALS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
@@ -313,6 +386,72 @@ mod tests {
|
||||
assert!(!path.exists(), "the endpoint file goes with the app");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_instance_or_safe_mode_launch_keeps_its_files() {
|
||||
let (path, _dir, file) = folder("own");
|
||||
let (primary, rx) = primary(&path);
|
||||
for (new_instance, safe_mode) in [(true, false), (false, true)] {
|
||||
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
|
||||
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
|
||||
}
|
||||
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
|
||||
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
|
||||
drop(primary);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_safe_mode_launch_leaves_later_launches_their_own_app() {
|
||||
let _globals = globals();
|
||||
let (path, _dir, file) = folder("safe-mode-alone");
|
||||
// With no app running, a Safe Mode launch runs without listening.
|
||||
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
|
||||
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
|
||||
// A plain launch after it starts its own app and takes later launches' files.
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
|
||||
panic!("the plain launch runs and listens")
|
||||
};
|
||||
assert!(path.exists());
|
||||
// An app that stays in Safe Mode after the choice gives that up.
|
||||
hold(Some(primary));
|
||||
resign();
|
||||
assert!(!path.exists(), "the endpoint file goes with resign");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_handed_to_an_app_staying_in_safe_mode_go_to_a_new_app_with_plug_ins() {
|
||||
let _globals = globals();
|
||||
// Nothing left over from a test that failed.
|
||||
resign();
|
||||
drop(take());
|
||||
let (path, _dir, file) = folder("safe-mode-later");
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
|
||||
hold(Some(primary));
|
||||
// A later launch handed its file over while the choice about a stopped plug-in was up.
|
||||
queue(vec![file.clone()]);
|
||||
let mut launched = Vec::new();
|
||||
let here = take_for_frame(true, |files| {
|
||||
launched = files.to_vec();
|
||||
Ok(())
|
||||
});
|
||||
assert!(here.is_empty(), "nothing opens in the Safe Mode app");
|
||||
assert_eq!(launched, std::slice::from_ref(&file), "a new app with plug-ins opens it");
|
||||
assert!(!path.exists(), "the app resigned before starting the new one");
|
||||
// When the new app can't start, the file opens here rather than being lost.
|
||||
queue(vec![file.clone()]);
|
||||
assert_eq!(take_for_frame(true, |_| Err(io::Error::other("no program"))), std::slice::from_ref(&file));
|
||||
// An app with plug-ins opens what it is handed.
|
||||
queue(vec![file.clone()]);
|
||||
assert_eq!(take_for_frame(false, |_| panic!("no new app")), [file]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_app_takes_every_name_as_a_file() {
|
||||
let command = app_with_plug_ins(Path::new("vectorcraft"), &["-a.svg".to_owned(), "b.svg".to_owned()]);
|
||||
let args: Vec<_> = command.get_args().collect();
|
||||
assert_eq!(args, ["--", "-a.svg", "b.svg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
|
||||
let (path, _dir, file) = folder("refused");
|
||||
|
||||
@@ -36,6 +36,33 @@ fn shortcut_overrides_from_an_earlier_version_load() {
|
||||
assert!(km.problems().iter().any(|p| format!("{p:?}") == r#"UnknownCommand { key: "test.unknown" }"#), "reported");
|
||||
}
|
||||
|
||||
/// The command line's files wait for the choice about a stopped plug-in, so they open with the
|
||||
/// plug-ins it loads; with no choice up they open at once.
|
||||
#[test]
|
||||
fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() {
|
||||
let temp = tempfile::Builder::new().prefix("vectorcraft-held-files-").tempdir().unwrap();
|
||||
let file = temp.path().join("a.svg");
|
||||
std::fs::write(&file, r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>"#).unwrap();
|
||||
let files = vec![file.to_string_lossy().into_owned()];
|
||||
// The files the app reads to open them.
|
||||
let read = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let reads = read.clone();
|
||||
let services = vectorcraft_ui_egui::Services {
|
||||
read: Some(Box::new(move |p: &str| {
|
||||
reads.borrow_mut().push(p.to_owned());
|
||||
std::fs::read(p).map_err(|e| e.to_string())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services);
|
||||
app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"}));
|
||||
assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up");
|
||||
assert!(read.borrow().is_empty(), "nothing opened before the choice");
|
||||
app.ui.stopped_plugin = None;
|
||||
assert!(open_or_hold(&mut app, files.clone()).is_empty());
|
||||
assert_eq!(*read.borrow(), files, "opened with no choice up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_files_unminimizes_and_focuses_the_window() {
|
||||
let ctx = egui::Context::default();
|
||||
@@ -164,6 +191,60 @@ fn the_system_title_bar_preference_keeps_the_window_decorations() {
|
||||
assert_eq!(super::native_options(true).viewport.decorations, Some(false));
|
||||
}
|
||||
|
||||
/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where
|
||||
/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe
|
||||
/// decides, and `VECTORCRAFT_TITLEBAR` takes precedence over both.
|
||||
#[test]
|
||||
fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
|
||||
assert!(!super::opted_into_app_title_bar(None), "no preferences: the default");
|
||||
let off = ui_state_with_prefs(serde_json::json!({"appTitleBar": false}));
|
||||
assert!(!super::opted_into_app_title_bar(Some(&off)));
|
||||
let on = ui_state_with_prefs(serde_json::json!({"appTitleBar": true}));
|
||||
assert!(super::opted_into_app_title_bar(Some(&on)));
|
||||
|
||||
// (probed_app, overridden, forced_to_x11): without the preference, then with it.
|
||||
let cases = [
|
||||
((false, None, false), false, true), // KDE, Sway, X11: the desktop frame
|
||||
((true, None, false), true, true), // GNOME on Wayland: the app frame either way
|
||||
((true, None, true), false, true), // GNOME, the window opened through XWayland
|
||||
((false, Some(true), false), true, true), // VECTORCRAFT_TITLEBAR=app
|
||||
((false, Some(true), true), true, true), // VECTORCRAFT_TITLEBAR=app, the window opened through XWayland
|
||||
((true, Some(false), false), false, false), // VECTORCRAFT_TITLEBAR=desktop takes precedence over the preference
|
||||
((false, Some(false), true), false, false),
|
||||
];
|
||||
for ((probed_app, overridden, forced_to_x11), without, with) in cases {
|
||||
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, false), without, "{probed_app} {overridden:?} {forced_to_x11}");
|
||||
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, true), with, "{probed_app} {overridden:?} {forced_to_x11}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
|
||||
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
|
||||
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
|
||||
#[test]
|
||||
fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
use craft_window::{Button, Frame, Layout};
|
||||
let gnome = Layout { left: vec![Button::Close], right: vec![] };
|
||||
let cases = [
|
||||
// (probed, overridden, forced_to_x11, opted_into_app), expected
|
||||
((Frame::Desktop, None, false, false), Frame::Desktop),
|
||||
((Frame::Desktop, None, false, true), Frame::App(Layout::default())),
|
||||
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
|
||||
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
|
||||
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
|
||||
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
|
||||
];
|
||||
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
|
||||
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
|
||||
assert_eq!(super::start_frame(probed, overridden, forced_to_x11, opted_into_app), expected, "{label}");
|
||||
}
|
||||
// With both preferences on, System Title Bar takes precedence: the desktop draws the frame.
|
||||
let both = super::start_frame(Frame::Desktop, None, false, true);
|
||||
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
|
||||
}
|
||||
|
||||
/// The file extensions the macOS bundle declares: its document types and its own exported type.
|
||||
fn plist_extensions(plist: &str) -> Vec<&str> {
|
||||
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
|
||||
|
||||
@@ -46,6 +46,53 @@ pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::Ui
|
||||
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the user asked for VectorCraft's own title bar in Preferences › User Interface ›
|
||||
/// VectorCraft Title Bar on Every Desktop (Linux and the BSDs). Read like
|
||||
/// [`opted_into_system_title_bar`]; a missing or unreadable value is `false` (the default).
|
||||
pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
saved.map(|ui| ui.engine_prefs.get("appTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the app draws the frame on this start, before the System Title Bar preference is
|
||||
/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and
|
||||
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when it is
|
||||
/// set; VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
|
||||
/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe
|
||||
/// decides.
|
||||
pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> bool {
|
||||
match overridden {
|
||||
Some(app) => app,
|
||||
None => opted_into_app || (probed_app && !forced_to_x11),
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame this start uses, before the System Title Bar preference is applied
|
||||
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
|
||||
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
|
||||
/// layout, since `custom_titlebar_from` reads only which frame it is.
|
||||
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
|
||||
let probed_app = matches!(probed, craft_window::Frame::App(_));
|
||||
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
|
||||
(true, frame @ craft_window::Frame::App(_)) => frame,
|
||||
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
|
||||
(false, _) => craft_window::Frame::Desktop,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `craft-window` probe's answer for this process (its override variable is
|
||||
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
|
||||
fn probed_choice() -> &'static craft_window::Choice {
|
||||
static CHOICE: std::sync::OnceLock<craft_window::Choice> = std::sync::OnceLock::new();
|
||||
CHOICE.get_or_init(|| craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT")))
|
||||
}
|
||||
|
||||
/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences ›
|
||||
/// User Interface › VectorCraft Title Bar on Every Desktop does not apply while it is set. Always
|
||||
/// `false` on macOS and Windows.
|
||||
pub(crate) fn titlebar_from_env() -> bool {
|
||||
cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some()
|
||||
}
|
||||
|
||||
/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate
|
||||
/// decided and the user's System Title Bar preference.
|
||||
///
|
||||
@@ -82,24 +129,27 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
|
||||
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
|
||||
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
|
||||
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
|
||||
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins.
|
||||
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins,
|
||||
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
|
||||
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
let choice = craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"));
|
||||
let choice = probed_choice();
|
||||
let opted_into_system = opted_into_system_title_bar(saved);
|
||||
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
|
||||
// ignores the frame there).
|
||||
let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// When the window will actually open on X11 (XWayland) — the user asked for it *and* the X11
|
||||
// libraries are present, the same two conditions the launch path checks below — that run is
|
||||
// effectively X11, so keep the native frame. If the libraries are missing, startup stays on
|
||||
// Wayland, so the probe's own decision (app-drawn on GNOME) must stand.
|
||||
let forced_to_x11 = {
|
||||
let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
|
||||
// `overridden() == None` means the probe decided (no VECTORCRAFT_TITLEBAR). When the window
|
||||
// will actually open on X11 (XWayland) — the user asked for it *and* the X11 libraries are
|
||||
// present, the same two conditions the launch path checks below — that run is effectively
|
||||
// X11, so keep the native frame. If the libraries are missing, startup stays on Wayland, so
|
||||
// the probe's own decision (app-drawn on GNOME) must stand.
|
||||
let forced_to_x11 = xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found();
|
||||
if choice.overridden().is_none() && forced_to_x11 {
|
||||
return custom_titlebar_from(&craft_window::Frame::Desktop, opted_into_system);
|
||||
}
|
||||
}
|
||||
custom_titlebar_from(choice.frame(), opted_into_system)
|
||||
xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found()
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let forced_to_x11 = false;
|
||||
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
|
||||
custom_titlebar_from(&frame, opted_into_system)
|
||||
}
|
||||
|
||||
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
|
||||
@@ -13,6 +13,13 @@
|
||||
//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame,
|
||||
//! so they don't run a shortcut bound to Alt and a digit.
|
||||
//!
|
||||
//! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right,
|
||||
//! Home, Up and Page Up, and Windows still composes the code from them. They are told from the
|
||||
//! separate navigation keys by the extended-key flag, which only the separate keys set
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input#extended-key-flag>),
|
||||
//! so with Alt held they count as digits and are taken out of the frame too, rather than moving
|
||||
//! the caret before the character arrives.
|
||||
//!
|
||||
//! egui reports a keypad digit as the same key as the digit above the letters, so the other
|
||||
//! platforms, whose systems have no such convention, can't tell them apart either.
|
||||
|
||||
@@ -28,10 +35,20 @@ const WM_CHAR: u32 = 0x0102;
|
||||
const WM_SYSKEYDOWN: u32 = 0x0104;
|
||||
const WM_SYSKEYUP: u32 = 0x0105;
|
||||
const WM_SYSCHAR: u32 = 0x0106;
|
||||
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. With it off the keys
|
||||
/// are Insert, End, … and type no code.
|
||||
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on.
|
||||
const VK_NUMPAD0: usize = 0x60;
|
||||
const VK_NUMPAD9: usize = 0x69;
|
||||
/// The keypad's virtual keys with NumLock off, by digit (`winuser.h`): `VK_INSERT`, `VK_END`,
|
||||
/// `VK_DOWN`, `VK_NEXT`, `VK_LEFT`, `VK_CLEAR`, `VK_RIGHT`, `VK_HOME`, `VK_UP` and `VK_PRIOR`.
|
||||
const NUMLOCK_OFF_KEYS: [usize; 10] = [0x2D, 0x23, 0x28, 0x22, 0x25, 0x0C, 0x27, 0x24, 0x26, 0x21];
|
||||
/// The keys egui reports for the keypad with NumLock off, by digit (Clear has no egui key, so it
|
||||
/// comes as the top-row digit key, `Num5`).
|
||||
const NUMLOCK_OFF_EGUI_KEYS: [Key; 10] =
|
||||
[Key::Insert, Key::End, Key::ArrowDown, Key::PageDown, Key::ArrowLeft, Key::Num5, Key::ArrowRight, Key::Home, Key::ArrowUp, Key::PageUp];
|
||||
const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9];
|
||||
/// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the
|
||||
/// keypad (the keypad's own keys clear it).
|
||||
const EXTENDED_KEY: isize = 1 << 24;
|
||||
/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt.
|
||||
const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5];
|
||||
|
||||
@@ -51,23 +68,42 @@ struct AltCodes {
|
||||
high: Option<u16>,
|
||||
/// Characters the codes typed, for the next frame.
|
||||
typed: String,
|
||||
/// Keypad digit presses and releases with Alt held since the last frame, which egui reports
|
||||
/// as Alt and a digit: taken out of the frame.
|
||||
keypad_events: usize,
|
||||
/// The digits of the keypad presses and releases with Alt held since the last frame, which
|
||||
/// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken
|
||||
/// out of the frame.
|
||||
keypad_events: Vec<usize>,
|
||||
}
|
||||
|
||||
/// The digit a keypad key stands for in an Alt code: `wparam` is its virtual-key code and
|
||||
/// `lparam` the message's flags.
|
||||
fn keypad_digit(wparam: usize, lparam: isize) -> Option<usize> {
|
||||
if (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam) {
|
||||
return Some(wparam - VK_NUMPAD0);
|
||||
}
|
||||
if lparam & EXTENDED_KEY != 0 {
|
||||
return None;
|
||||
}
|
||||
NUMLOCK_OFF_KEYS.iter().position(|&k| k == wparam)
|
||||
}
|
||||
|
||||
impl AltCodes {
|
||||
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit).
|
||||
fn message(&mut self, message: u32, wparam: usize) {
|
||||
let keypad = (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam);
|
||||
match message {
|
||||
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit)
|
||||
/// and `lparam` (its flags).
|
||||
fn message(&mut self, message: u32, wparam: usize, lparam: isize) {
|
||||
let keypad = match message {
|
||||
WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(d) = keypad {
|
||||
// Windows sends a key pressed with Alt held as a system key.
|
||||
WM_SYSKEYDOWN if keypad => {
|
||||
if message == WM_SYSKEYDOWN {
|
||||
self.digits += 1;
|
||||
self.keypad_events += 1;
|
||||
self.armed = false;
|
||||
}
|
||||
WM_SYSKEYUP if keypad => self.keypad_events += 1,
|
||||
self.keypad_events.push(d);
|
||||
return;
|
||||
}
|
||||
match message {
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {}
|
||||
// Any other key ends the sequence and keeps its own meaning.
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(),
|
||||
@@ -99,14 +135,23 @@ impl AltCodes {
|
||||
/// out the keypad digits typed with Alt held.
|
||||
fn drain(&mut self, events: &mut Vec<Event>) {
|
||||
let mut keypad = std::mem::take(&mut self.keypad_events);
|
||||
if keypad > 0 {
|
||||
if !keypad.is_empty() {
|
||||
events.retain(|e| {
|
||||
let digit = matches!(e, Event::Key { key: Key::Num0 | Key::Num1 | Key::Num2 | Key::Num3 | Key::Num4 | Key::Num5 | Key::Num6 | Key::Num7 | Key::Num8 | Key::Num9, modifiers, .. } if modifiers.alt);
|
||||
if digit && keypad > 0 {
|
||||
keypad -= 1;
|
||||
return false;
|
||||
let Event::Key { key, modifiers, .. } = e else {
|
||||
return true;
|
||||
};
|
||||
if !modifiers.alt {
|
||||
return true;
|
||||
}
|
||||
// The first keypad key still to take out that egui reports as `key`.
|
||||
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
|
||||
match keypad.iter().position(stands_for) {
|
||||
Some(i) => {
|
||||
keypad.remove(i);
|
||||
false
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
if !self.typed.is_empty() {
|
||||
@@ -129,7 +174,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) {
|
||||
if (WM_KEYDOWN..=WM_SYSCHAR).contains(&msg.message) {
|
||||
CODES.with(|c| {
|
||||
if let Ok(mut c) = c.try_borrow_mut() {
|
||||
c.message(msg.message, msg.wParam.0);
|
||||
c.message(msg.message, msg.wParam.0, msg.lParam.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -152,14 +197,14 @@ mod tests {
|
||||
|
||||
/// Alt held, keypad digits `code`, Alt released, and the character Windows then posts.
|
||||
fn alt_code(c: &mut AltCodes, code: &str, posted: u16) {
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
for d in code.bytes() {
|
||||
let vk = VK_NUMPAD0 + usize::from(d - b'0');
|
||||
c.message(WM_SYSKEYDOWN, vk);
|
||||
c.message(WM_SYSKEYUP, vk);
|
||||
c.message(WM_SYSKEYDOWN, vk, 0);
|
||||
c.message(WM_SYSKEYUP, vk, 0);
|
||||
}
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, usize::from(posted));
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(posted), 0);
|
||||
}
|
||||
|
||||
fn key(key: Key, alt: bool, pressed: bool) -> Event {
|
||||
@@ -186,11 +231,11 @@ mod tests {
|
||||
fn a_character_without_a_code_before_it_is_left_to_winit() {
|
||||
let mut c = AltCodes::default();
|
||||
// A plain key press's character (winit types it), and Alt pressed and released alone.
|
||||
c.message(WM_KEYDOWN, 0x41);
|
||||
c.message(WM_CHAR, usize::from(b'a'));
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, usize::from(b'b'));
|
||||
c.message(WM_KEYDOWN, 0x41, 0);
|
||||
c.message(WM_CHAR, usize::from(b'a'), 0);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(b'b'), 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert!(events.is_empty(), "{events:?}");
|
||||
@@ -199,12 +244,12 @@ mod tests {
|
||||
#[test]
|
||||
fn another_key_while_alt_is_held_cancels_the_code() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
// Alt+F: a shortcut, not a code.
|
||||
c.message(WM_SYSKEYDOWN, 0x46);
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, 0x41);
|
||||
c.message(WM_SYSKEYDOWN, 0x46, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}");
|
||||
@@ -213,13 +258,81 @@ mod tests {
|
||||
#[test]
|
||||
fn a_code_above_the_basic_plane_arrives_as_two_halves() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
|
||||
c.message(WM_KEYUP, ALT);
|
||||
c.message(WM_CHAR, 0xD83D);
|
||||
c.message(WM_CHAR, 0xDE00);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0xD83D, 0);
|
||||
c.message(WM_CHAR, 0xDE00, 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("😀".into())]);
|
||||
}
|
||||
|
||||
/// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the
|
||||
/// extended-key bit), Alt released, and the character Windows then posts.
|
||||
fn alt_code_numlock_off(c: &mut AltCodes, code: &str, posted: u16) {
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
for d in code.bytes() {
|
||||
let vk = NUMLOCK_OFF_KEYS[usize::from(d - b'0')];
|
||||
c.message(WM_SYSKEYDOWN, vk, 0);
|
||||
c.message(WM_SYSKEYUP, vk, 0);
|
||||
}
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(posted), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() {
|
||||
let mut c = AltCodes::default();
|
||||
alt_code_numlock_off(&mut c, "0176", 0xB0);
|
||||
// What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a
|
||||
// release each, then a plain Home typed after Alt came up.
|
||||
let mut events = vec![];
|
||||
for k in [Key::Insert, Key::End, Key::Home, Key::ArrowRight] {
|
||||
events.push(key(k, true, true));
|
||||
events.push(key(k, true, false));
|
||||
}
|
||||
events.push(key(Key::Home, false, true));
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_numlock_off_keypad_five_counts_too() {
|
||||
let mut c = AltCodes::default();
|
||||
// Keypad 5 is Clear, which egui reports as the top-row 5. 0151 uses Insert, End and Clear;
|
||||
// 0234 uses Insert, Down, Page Down and Left.
|
||||
alt_code_numlock_off(&mut c, "0151", 0x2014);
|
||||
alt_code_numlock_off(&mut c, "0234", 0xEA);
|
||||
let mut events =
|
||||
vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("—ê".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0);
|
||||
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[1], 0);
|
||||
// Alt+Home on the separate Home key (extended): a shortcut, not a digit.
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numlock_off_keys_without_alt_are_left_alone() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_KEYDOWN, NUMLOCK_OFF_KEYS[7], 0);
|
||||
c.message(WM_KEYUP, NUMLOCK_OFF_KEYS[7], 0);
|
||||
let mut events = vec![key(Key::Home, false, true), key(Key::Home, false, false)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--version", "--help"] {
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
|
||||
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
|
||||
}
|
||||
// Headless work is the CLI's: the usage says where to go.
|
||||
@@ -74,3 +74,27 @@ fn help_prints_usage_and_exits_before_startup() {
|
||||
fn help_wins_over_a_bad_control_port_variable() {
|
||||
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
|
||||
}
|
||||
|
||||
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
|
||||
/// plug-ins; a later `--help` still wins.
|
||||
#[test]
|
||||
fn an_unknown_option_is_an_error_and_not_a_file() {
|
||||
for args in [&["--safe-mod"][..], &["drawing.svg", "--safe-mod"], &["-x"]] {
|
||||
let out = run(args, &[]);
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}");
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
let unknown = args.iter().find(|a| a.starts_with('-')).unwrap();
|
||||
assert_eq!(
|
||||
stderr,
|
||||
format!("vectorcraft: unknown option {unknown}; see vectorcraft --help, or put -- before a file whose name starts with '-'\n"),
|
||||
"{args:?}"
|
||||
);
|
||||
}
|
||||
prints_usage(&["--safe-mod", "--help"], &[]);
|
||||
// After `--`, a name starting with '-' is a file: the run goes on to the control port, which
|
||||
// `run` makes fail.
|
||||
let out = run(&["--", "-x.svg"], &[]);
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains("unknown option"), "{stderr}");
|
||||
}
|
||||
@@ -29,6 +29,14 @@ const MAX_DOCUMENT_CELLS: usize = 1 << 18;
|
||||
/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers).
|
||||
const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20;
|
||||
|
||||
/// Child references inspected, page rectangles produced, and outline segments retained, in all
|
||||
/// (shared objects are visited once per link, so each visit is charged). Real documents stay
|
||||
/// within a few times [`MAX_NODES`]; this leaves ~30x headroom over that.
|
||||
const MAX_DOCUMENT_WORK: usize = 1 << 24;
|
||||
|
||||
/// Owned layer-name characters kept in all (each visit of a shared object keeps its own copy).
|
||||
const MAX_DOCUMENT_NAME_CHARS: usize = 16 << 20;
|
||||
|
||||
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
|
||||
/// documents are read with what their embedding document left, so linking or embedding the
|
||||
/// same content many times can't multiply the work.
|
||||
@@ -44,6 +52,10 @@ pub(crate) struct Budget {
|
||||
pub(crate) cells: usize,
|
||||
/// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all).
|
||||
pub(crate) pressure: usize,
|
||||
/// Child references, page rectangles and outline segments ([`MAX_DOCUMENT_WORK`] in all).
|
||||
pub(crate) work: usize,
|
||||
/// Layer-name characters ([`MAX_DOCUMENT_NAME_CHARS`] in all).
|
||||
pub(crate) name_chars: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
@@ -53,7 +65,15 @@ impl Budget {
|
||||
chars: MAX_DOCUMENT_CHARS,
|
||||
cells: MAX_DOCUMENT_CELLS,
|
||||
pressure: MAX_DOCUMENT_PRESSURE_POINTS,
|
||||
work: MAX_DOCUMENT_WORK,
|
||||
name_chars: MAX_DOCUMENT_NAME_CHARS,
|
||||
};
|
||||
|
||||
/// Take `n` units of work, or fail the read.
|
||||
pub(crate) fn spend(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.work = self.work.checked_sub(n).ok_or(Error::Limit("too much shared geometry or page data"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a document: archive, `doc.dat` and the model.
|
||||
@@ -192,6 +212,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
return Ok(None);
|
||||
}
|
||||
let pages = pages(s, spread);
|
||||
self.budget.spend(pages.len() + 1)?;
|
||||
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
|
||||
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
|
||||
x0: 0.0,
|
||||
@@ -214,7 +235,10 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
let mut mask = None;
|
||||
for c in s.objs(parent, b"Chld") {
|
||||
let kids = s.objs(parent, b"Chld");
|
||||
// Invisible masks and skipped children cost no node, so the visit is charged here.
|
||||
self.budget.spend(kids.len())?;
|
||||
for c in kids {
|
||||
if s.is(c, b"MRst") {
|
||||
// A mask layer inside a group or layer masks that container.
|
||||
if s.bool(c, b"Visi") == Some(false) {
|
||||
@@ -254,7 +278,8 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
let world = local.then(parent);
|
||||
let class = s.class(id).unwrap_or(Tag(0));
|
||||
// A layer name is short; a long one is cut, as every visit of a shared object keeps a copy.
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS).collect();
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS.min(self.budget.name_chars)).collect();
|
||||
self.budget.name_chars -= name.chars().count();
|
||||
let visible = s.bool(id, b"Visi").unwrap_or(true);
|
||||
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
|
||||
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
|
||||
@@ -312,6 +337,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
self.warn(format!("a {} that could not be read", describe(class)));
|
||||
return Ok(Kind::Unsupported);
|
||||
};
|
||||
self.budget.spend(local.subpaths.iter().map(|sp| sp.segments.len() + 1).sum())?;
|
||||
let (fills, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
|
||||
}
|
||||
@@ -645,3 +671,15 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_work_is_bounded() {
|
||||
let mut b = Budget::FULL;
|
||||
assert!(b.spend(MAX_DOCUMENT_WORK).is_ok());
|
||||
assert_eq!(b.spend(1), Err(Error::Limit("too much shared geometry or page data")));
|
||||
}
|
||||
}
|
||||
@@ -238,12 +238,13 @@ pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<Pai
|
||||
};
|
||||
let grad = s.obj(fill, b"Grad")?;
|
||||
let cols = s.objs(grad, b"Cols");
|
||||
let posn: Vec<Vec<f64>> = match s.field(grad, b"Posn") {
|
||||
Some(Value::Array(a)) => a.iter().filter_map(floats).collect(),
|
||||
_ => Vec::new(),
|
||||
// Convert only the positions that pair with a colour, as shared attributes repeat this per run.
|
||||
let posn: &[Value] = match s.field(grad, b"Posn") {
|
||||
Some(Value::Array(a)) => a,
|
||||
_ => &[],
|
||||
};
|
||||
let mut stops = Vec::new();
|
||||
for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) {
|
||||
for (c, p) in cols.iter().zip(posn.iter().filter_map(floats)).take(MAX_STOPS) {
|
||||
let color = color(r, *c)?;
|
||||
let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0);
|
||||
|
||||
@@ -195,6 +195,11 @@ fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), worl
|
||||
if let Some(name) = s.entry(bitmap, b"Bckg") {
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
// The whole source is decoded for every layer that reads it, so charge it all, not only the crop.
|
||||
let Some(left) = r.budget.pixels.checked_sub(u64::from(width) * u64::from(height)) else {
|
||||
return Err(Error::Limit("embedded image pixels"));
|
||||
};
|
||||
r.budget.pixels = left;
|
||||
match original(r, name).and_then(|bytes| source_pixels(&bytes, width, height)) {
|
||||
Ok(pixels) => Some((width as usize, pixels)),
|
||||
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
|
||||
@@ -318,8 +323,10 @@ fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usiz
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
|
||||
let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| width.saturating_mul(bps).div_ceil(TILE));
|
||||
let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
|
||||
// A grid larger than the bitmap has tiles no crop can reach: don't convert or scan them on every reference.
|
||||
let tiles = width.saturating_mul(bps).div_ceil(TILE).saturating_mul(height.div_ceil(TILE));
|
||||
let states: Vec<u8> = match s.field(bitmap, &tag(b"Sta", c)) {
|
||||
Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
|
||||
Some(Value::Array(a)) => a.iter().take(tiles).map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
(tw, th, states)
|
||||
|
||||
@@ -51,6 +51,9 @@ const MAX_TABLE_LINES: usize = 4096;
|
||||
/// Cells a table may have (rows × columns): each becomes a text object with its edge lines.
|
||||
const MAX_TABLE_CELLS: usize = 1 << 16;
|
||||
|
||||
/// Work charged for each copy of a run's formatting a table cell keeps.
|
||||
const TABLE_RUN_COST: usize = 16;
|
||||
|
||||
/// A table node (`TxtT`): the grid, the cells' text and the lines on the cell edges.
|
||||
pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
|
||||
let s = r.s;
|
||||
@@ -108,9 +111,10 @@ pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
|
||||
let mut parts = run.text.split(CELL_BREAK).peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if !part.is_empty() {
|
||||
// Each cell keeps its own copy of the run's formatting, so each copy is charged.
|
||||
match target.and_then(|i| cells.get_mut(i)) {
|
||||
Some(cell) => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
|
||||
None => extra = true,
|
||||
Some(cell) if r.budget.spend(TABLE_RUN_COST).is_ok() => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
|
||||
_ => extra = true,
|
||||
}
|
||||
}
|
||||
if parts.peek().is_some() {
|
||||
@@ -157,6 +161,13 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
let mut placeholders = false;
|
||||
let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
|
||||
for block in s.objs(story, b"Blok") {
|
||||
// Shared blocks and run lists are visited once per link, so every visit is charged, empty or not.
|
||||
let paragraph_runs = s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default();
|
||||
let attribute_runs = s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default();
|
||||
if r.budget.spend(1 + paragraph_runs.len() + attribute_runs.len()).is_err() {
|
||||
r.warn("text beyond the work one document may hold (truncated)");
|
||||
break;
|
||||
}
|
||||
let Some(glyphs) = s.obj(block, b"Glyp") else {
|
||||
r.warn("a text block without readable characters (left out)");
|
||||
continue;
|
||||
@@ -209,7 +220,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
// Paragraph formats by end index; a run without an index covers the rest of the block.
|
||||
let mut paragraphs: Vec<(usize, Paragraph)> = Vec::new();
|
||||
let mut open: Option<Paragraph> = None;
|
||||
for run in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() {
|
||||
for run in paragraph_runs {
|
||||
let Some(attrs) = s.obj(run, b"Item") else { continue };
|
||||
let a = paragraph(r, attrs);
|
||||
first_align.get_or_insert(a.align);
|
||||
@@ -238,7 +249,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
}
|
||||
};
|
||||
let mut start = 0usize;
|
||||
for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
|
||||
for run in attribute_runs {
|
||||
let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
|
||||
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
|
||||
continue;
|
||||
|
||||
@@ -475,6 +475,10 @@ pub struct PatternBrush {
|
||||
pub side_frame: Option<Rect>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub side_swatch: Option<String>,
|
||||
/// Art for the corners where the path turns towards the side tile's top (`-y`); `inner_corner`
|
||||
/// is the art for the corners where it turns the other way. Both are drawn as the corner that
|
||||
/// joins a side tile on its right to one below it, and each corner tile is turned so that
|
||||
/// those two arms meet the sides.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub outer_corner: Option<Node>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -299,6 +299,101 @@ fn pattern_places_corner_tiles() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern brush whose corner tiles have a 4 × 4 pt frame and, as art, a 2 × 2 pt square in the
|
||||
/// top-left quarter of the frame. Corner art joins a side tile on its right to one below it, so
|
||||
/// that quarter is on the outside of the turn. `inner` and `outer` say which kinds of corner have
|
||||
/// art; `flips` are the brush's Flip Along and Flip Across.
|
||||
fn marked_corner_brush(inner: bool, outer: bool, (flip_along, flip_across): (bool, bool)) -> Brush {
|
||||
let marker =
|
||||
Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, -2.0, 2.0, 0.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let mut b = pattern_brush(PatternFit::Stretch, false);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let frame = Some(Rect::new(0.0, -2.0, 4.0, 2.0));
|
||||
if inner {
|
||||
(p.inner_corner, p.inner_corner_frame) = (Some(marker.clone()), frame);
|
||||
}
|
||||
if outer {
|
||||
(p.outer_corner, p.outer_corner_frame) = (Some(marker), frame);
|
||||
}
|
||||
(p.flip_along, p.flip_across) = (flip_along, flip_across);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Each combination of corner art (both kinds, inner only, outer only) and of the two flips.
|
||||
fn marked_corner_brushes() -> Vec<(String, Brush)> {
|
||||
let mut v = vec![];
|
||||
for (inner, outer) in [(true, true), (true, false), (false, true)] {
|
||||
for flips in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
v.push((format!("inner {inner}, outer {outer}, flips {flips:?}"), marked_corner_brush(inner, outer, flips)));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The bounds of the 2 × 2 pt corner markers among `out`, turned or not.
|
||||
fn marker_bounds(out: &[Node]) -> Vec<Rect> {
|
||||
out.iter().filter_map(Node::geometric_bounds).filter(|r| r.width() < 3.0 && r.height() < 3.0).collect()
|
||||
}
|
||||
|
||||
/// Corner tiles are square to the sides at a right angle and turn 90° with each turn of the path:
|
||||
/// on a square drawn either way round, each corner's marker fills the quarter of the band's corner
|
||||
/// outside the turn, with the brush flipped or not and with art for one kind of corner only
|
||||
/// (#6110).
|
||||
#[test]
|
||||
fn pattern_corner_tiles_are_square_to_the_sides() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let sq = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
|
||||
let mut reversed = BezPath::new();
|
||||
reversed.move_to((0.0, 0.0));
|
||||
for (x, y) in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] {
|
||||
reversed.line_to((x, y));
|
||||
}
|
||||
reversed.close_path();
|
||||
// The square turns the same way at all four corners, and the reversed square the other way,
|
||||
// so one draws only inner corner tiles and the other only outer ones.
|
||||
for (name, brush) in marked_corner_brushes() {
|
||||
for path in [&sq, &reversed] {
|
||||
let out = stroke_pieces(&doc, &brush, path, &stroke(1.0));
|
||||
let marks = marker_bounds(&out);
|
||||
assert_eq!(marks.len(), 4, "{name}: one marker a corner");
|
||||
for (corner, outside) in SQUARE_CORNERS {
|
||||
let want = Rect::from_points(corner, outside);
|
||||
assert!(
|
||||
marks
|
||||
.iter()
|
||||
.any(|r| near(r.x0, want.x0, 1e-6) && near(r.y0, want.y0, 1e-6) && near(r.x1, want.x1, 1e-6) && near(r.y1, want.y1, 1e-6)),
|
||||
"{name}: the marker at {corner:?} fills {want:?}: {marks:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// At a corner that is not a right angle, a corner tile splits the difference between the two
|
||||
/// sides: its marker lies on the line that halves the angle, outside the turn, for sharp and
|
||||
/// shallow turns either way. Near a hairpin the marker moves smoothly towards the line the path
|
||||
/// arrives on.
|
||||
#[test]
|
||||
fn pattern_corner_tiles_sit_on_the_corners_diagonal() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
for (name, brush) in marked_corner_brushes() {
|
||||
for turn in [-179.9_f64, -170.0, -135.0, -60.0, -45.0, 45.0, 60.0, 135.0, 170.0, 179.9] {
|
||||
let (a, b) = (Vec2::new(1.0, 0.0), Vec2::new(turn.to_radians().cos(), turn.to_radians().sin()));
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((50.0, 0.0));
|
||||
bp.line_to(Point::new(50.0, 0.0) + b * 50.0);
|
||||
let out = stroke_pieces(&doc, &brush, &bp, &stroke(1.0));
|
||||
let marks = marker_bounds(&out);
|
||||
assert_eq!(marks.len(), 1, "{name}, {turn}°: one corner marker");
|
||||
let away = a - b;
|
||||
let want = Point::new(50.0, 0.0) + away / away.hypot() * 2.0_f64.sqrt();
|
||||
assert!(marks[0].center().distance(want) < 1e-6, "{name}, {turn}°: the marker is at {:?}, not {want:?}", marks[0].center());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 10 × 4 pt side tile of [`pattern_brush`] with the given corner sources and no corner art.
|
||||
fn auto_corner_brush(outer: Option<CornerSource>, inner: Option<CornerSource>) -> Brush {
|
||||
let mut b = pattern_brush(PatternFit::Stretch, false);
|
||||
|
||||
@@ -879,12 +879,16 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
};
|
||||
trims.push(None);
|
||||
corner_half = corner_half.max(bb.width() * k / 2.0);
|
||||
let bis = a + b;
|
||||
let bis = if bis.hypot() < 1e-9 { a } else { bis / bis.hypot() };
|
||||
let xf = Affine::translate(t.verts[i].to_vec2())
|
||||
* Affine::rotate(bis.y.atan2(bis.x))
|
||||
* Affine::scale(k)
|
||||
* Affine::translate(-bb.center().to_vec2());
|
||||
// Inner and outer corner art is the corner that joins a side tile on its right to one
|
||||
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
|
||||
// turned so that the line halving its arms lies on the line halving the sides at the
|
||||
// corner, back along the incoming side and on along the outgoing one: at a right angle
|
||||
// the arms meet the side tiles, and at other angles the difference is split between
|
||||
// the two sides (#6110).
|
||||
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
|
||||
let sides = b - a;
|
||||
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
|
||||
let mut n = art.clone();
|
||||
n.transform(xf, true);
|
||||
out.take(Some(n));
|
||||
|
||||
@@ -308,6 +308,78 @@ impl Default for DxfOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// A named set of DXF options (the `dxfPreset` param): the options it sets, and the ones a set of
|
||||
/// options matches.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum DxfPreset {
|
||||
/// The options as chosen (the export's defaults for those left out).
|
||||
#[default]
|
||||
Custom,
|
||||
/// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight
|
||||
/// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize
|
||||
/// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths),
|
||||
/// and placed images as PNG.
|
||||
Cnc,
|
||||
}
|
||||
|
||||
impl DxfPreset {
|
||||
pub const ALL: [Self; 2] = [Self::Custom, Self::Cnc];
|
||||
|
||||
/// The `dxfPreset` param value.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Custom => "custom",
|
||||
Self::Cnc => "cnc",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Custom => "Custom",
|
||||
Self::Cnc => "CNC / CAM",
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset by id (`custom`, `cnc`), any case.
|
||||
pub fn from_id(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|p| s.trim().eq_ignore_ascii_case(p.id()))
|
||||
}
|
||||
|
||||
/// The options the preset sets (Custom: the defaults); the region and crop are the defaults.
|
||||
pub fn options(self) -> DxfOptions {
|
||||
match self {
|
||||
Self::Custom => DxfOptions::default(),
|
||||
Self::Cnc => DxfOptions {
|
||||
version: DxfVersion::R2000,
|
||||
unit: Unit::Millimeters,
|
||||
scale: 1.0,
|
||||
scale_lineweights: false,
|
||||
colors: ColorDepth::Aci256,
|
||||
raster: RasterFormat::Png,
|
||||
preserve: Preserve::Editability,
|
||||
alter_paths: false,
|
||||
outline_text: true,
|
||||
..DxfOptions::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset `o` matches: CNC / CAM when every option it sets is as it sets it, else Custom.
|
||||
pub fn of(o: &DxfOptions) -> Self {
|
||||
let c = Self::Cnc.options();
|
||||
let same = o.version == c.version
|
||||
&& o.unit == c.unit
|
||||
&& o.scale == c.scale
|
||||
&& o.scale_lineweights == c.scale_lineweights
|
||||
&& o.colors == c.colors
|
||||
&& o.raster == c.raster
|
||||
&& o.preserve == c.preserve
|
||||
&& o.alter_paths == c.alter_paths
|
||||
&& o.outline_text == c.outline_text;
|
||||
if same { Self::Cnc } else { Self::Custom }
|
||||
}
|
||||
}
|
||||
|
||||
/// An image file a drawing links to, to be written next to it under `name`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DxfImage {
|
||||
|
||||
@@ -823,6 +823,30 @@ fn units_scale_coordinates_and_set_insunits() {
|
||||
assert!(export(&d, &DxfOptions { scale: f64::NAN, ..opts(&d) }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines() {
|
||||
let mut d = text_doc("Cut", 20.0);
|
||||
let layer = d.layers[0].id;
|
||||
let frame = path(&mut d, shapes::rectangle(Rect::new(5.0, 5.0, 195.0, 95.0)), Paint::None, Paint::solid(Color::BLACK), 10.0);
|
||||
d.insert(Some(layer), usize::MAX, frame).unwrap();
|
||||
let o = DxfOptions { region: d.artboards[0].rect, ..DxfPreset::Cnc.options() };
|
||||
let out = export(&d, &o).unwrap();
|
||||
let p = pairs(&out.bytes);
|
||||
assert_eq!(header(&p, "$ACADVER").as_deref(), Some("AC1015"));
|
||||
assert_eq!(header(&p, "$INSUNITS").as_deref(), Some("4"));
|
||||
let k = kinds(&out);
|
||||
assert!(!k.iter().any(|k| matches!(k.as_str(), "TEXT" | "MTEXT" | "IMAGE")), "type is paths: {k:?}");
|
||||
assert!(k.len() > 2, "the glyphs' outlines: {k:?}");
|
||||
// The 10 pt stroke (wider than the widest lineweight) is one center line, not a filled outline.
|
||||
assert_eq!(k.last().map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
|
||||
assert_ne!(k.get(k.len() - 2).map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
|
||||
assert!(out.images.is_empty());
|
||||
assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_become_dxf_layers() {
|
||||
let mut d = shapes_doc();
|
||||
|
||||
@@ -231,6 +231,21 @@ impl GenericCmyk {
|
||||
}
|
||||
g[p] = -(0..3).map(|i| j[i][p] * r[i]).sum::<f32>();
|
||||
}
|
||||
// An ink at a bound whose descent direction points out of the box stays where it is; the step moves the other inks.
|
||||
for p in 0..3 {
|
||||
if (x[p] <= 0.0 && g[p] < 0.0) || (x[p] >= 1.0 && g[p] > 0.0) {
|
||||
a[p] = [0.0; 3];
|
||||
for row in &mut a {
|
||||
row[p] = 0.0;
|
||||
}
|
||||
a[p][p] = 1.0;
|
||||
g[p] = 0.0;
|
||||
}
|
||||
}
|
||||
// Every ink is held at a bound, or the gradient is zero: no step can lower the error.
|
||||
if g == [0.0; 3] {
|
||||
break;
|
||||
}
|
||||
let mut improved = false;
|
||||
for _ in 0..8 {
|
||||
let mut al = a;
|
||||
|
||||
@@ -259,6 +259,46 @@ fn generic_cmyk_black_round_trips_with_bpc() {
|
||||
assert!(raw.iter().all(|v| *v > 0.05), "{raw:?}");
|
||||
}
|
||||
|
||||
/// A color whose solve holds cyan at 0 separates to the same inks when its values change by a few
|
||||
/// float steps: hex ed1e79 with its red stepped one `f32` at a time over 4,001 values (about 0.00024
|
||||
/// in all) stays within 0.001 on every ink.
|
||||
#[test]
|
||||
fn generic_cmyk_separates_nearby_colors_at_the_gamut_edge_alike() {
|
||||
let c = cms();
|
||||
let pink = [237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0];
|
||||
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
|
||||
for step in -2000i32..=2000 {
|
||||
let mut rgb = pink;
|
||||
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
|
||||
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
|
||||
for i in 0..4 {
|
||||
lo[i] = lo[i].min(ink[i]);
|
||||
hi[i] = hi[i].max(ink[i]);
|
||||
}
|
||||
}
|
||||
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
|
||||
assert_eq!(lo[0], 0.0, "{lo:?}");
|
||||
}
|
||||
|
||||
/// A color whose solve holds cyan and magenta at 1 separates to the same inks when its values change
|
||||
/// by a few float steps: sRGB (0, 0, 0.25) with its blue stepped one `f32` at a time over 121 values
|
||||
/// stays within 0.001 on every ink.
|
||||
#[test]
|
||||
fn generic_cmyk_separates_nearby_colors_with_inks_at_full_alike() {
|
||||
let c = cms();
|
||||
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
|
||||
for step in -60i32..=60 {
|
||||
let blue = f32::from_bits(0.25f32.to_bits().wrapping_add_signed(step));
|
||||
let ink = c.srgb_to_cmyk([0.0, 0.0, blue], Intent::RelativeColorimetric);
|
||||
for i in 0..4 {
|
||||
lo[i] = lo[i].min(ink[i]);
|
||||
hi[i] = hi[i].max(ink[i]);
|
||||
}
|
||||
}
|
||||
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
|
||||
assert_eq!((lo[0], lo[1]), (1.0, 1.0), "{lo:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lab_colours_round_trip_through_the_cms() {
|
||||
let c = cms_no_bpc();
|
||||
|
||||
@@ -296,6 +296,28 @@ impl Appearance {
|
||||
scale(e, s);
|
||||
}
|
||||
}
|
||||
/// The id of Effect › SVG Filters' effect, whose `origin` parameter is a point of the document.
|
||||
pub const SVG_FILTER: &str = "svg.filter";
|
||||
|
||||
/// Does any effect (the object's or a fill's or stroke's) hold an SVG filter?
|
||||
pub fn has_svg_filter(&self) -> bool {
|
||||
self.effects.iter().chain(self.items.iter().flat_map(|i| i.effects().iter())).any(|e| e.id == Self::SVG_FILTER)
|
||||
}
|
||||
|
||||
/// Move the `origin` of every SVG filter effect (where its user space starts in the document)
|
||||
/// by `a`, as the object it is on moves.
|
||||
pub fn transform_svg_filters(&mut self, a: kurbo::Affine) {
|
||||
let items = self.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in self.effects.iter_mut().chain(items).filter(|e| e.id == Self::SVG_FILTER) {
|
||||
let at =
|
||||
|i: usize| e.params.get("origin").and_then(|o| o.get(i)).and_then(serde_json::Value::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let p = a * kurbo::Point::new(at(0), at(1));
|
||||
if p.x.is_finite() && p.y.is_finite() && e.params.is_object() {
|
||||
e.params["origin"] = serde_json::json!([p.x, p.y]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient paints of the fills and strokes.
|
||||
fn gradients_mut(&mut self) -> impl Iterator<Item = &mut vectorcraft_color::GradientPaint> {
|
||||
self.items.iter_mut().filter_map(|i| match i {
|
||||
|
||||
@@ -106,6 +106,60 @@ impl super::Document {
|
||||
d.layers.insert(0, Arc::new(layer));
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Where an artboard the size of artboard `i` goes on `side` of it, [`ARTBOARD_GAP`] away,
|
||||
/// when there is room for it there: every side within [`crate::MAX_COORD`] of the origin and
|
||||
/// no other artboard overlapping it (touching edges don't overlap). `None` when there is no
|
||||
/// such artboard or no room.
|
||||
pub fn room_beside_artboard(&self, i: usize, side: ArtboardSide) -> Option<Rect> {
|
||||
let src = self.artboards.get(i)?.rect;
|
||||
let r = src + side.offset(src);
|
||||
let in_canvas = [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD);
|
||||
let clear = self.artboards.iter().all(|a| !(r.x0 < a.rect.x1 && a.rect.x0 < r.x1 && r.y0 < a.rect.y1 && a.rect.y0 < r.y1));
|
||||
(in_canvas && clear).then_some(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// The space between an artboard and one added or duplicated beside it (VectorCraft's own value,
|
||||
/// the space New Artboard and Duplicate Artboards leave right of the last artboard).
|
||||
pub const ARTBOARD_GAP: f64 = 20.0;
|
||||
|
||||
/// A side of an artboard, where an artboard added or duplicated beside it goes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArtboardSide {
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl ArtboardSide {
|
||||
pub const ALL: [Self; 4] = [Self::Top, Self::Right, Self::Bottom, Self::Left];
|
||||
|
||||
/// The side a command's `side` param names: "left", "right", "top" or "bottom".
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|s| s.name() == name)
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Left => "left",
|
||||
Self::Right => "right",
|
||||
Self::Top => "top",
|
||||
Self::Bottom => "bottom",
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a copy of `r` moves to sit on this side of it, [`ARTBOARD_GAP`] away (y down).
|
||||
pub fn offset(self, r: Rect) -> vectorcraft_geom::Vec2 {
|
||||
let (w, h) = (r.width() + ARTBOARD_GAP, r.height() + ARTBOARD_GAP);
|
||||
match self {
|
||||
Self::Left => vectorcraft_geom::Vec2::new(-w, 0.0),
|
||||
Self::Right => vectorcraft_geom::Vec2::new(w, 0.0),
|
||||
Self::Top => vectorcraft_geom::Vec2::new(0.0, -h),
|
||||
Self::Bottom => vectorcraft_geom::Vec2::new(0.0, h),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's locked artboards ([`Document::locked_artboards`]).
|
||||
|
||||
@@ -11,12 +11,16 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::{Document, NodeId};
|
||||
|
||||
/// One asset: what it is called (its files' names) and the objects it exports, cropped to their
|
||||
/// visual bounds.
|
||||
/// visual bounds, or for a 3D asset its object's solids as a mesh file.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportAsset {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub nodes: Vec<NodeId>,
|
||||
/// A 3D asset's mesh format (`usda`, `usdz`, `gltf` or `obj`): its object exports as a 3D
|
||||
/// file. `None` for art exported as pictures.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format_3d: Option<String>,
|
||||
}
|
||||
|
||||
/// What the assets are named when they aren't named after their object: `Asset 1`, `Asset 2`…
|
||||
@@ -30,7 +34,16 @@ impl Document {
|
||||
|
||||
/// The name of the next unnamed asset: one more than the highest `Asset N` so far.
|
||||
pub fn next_asset_name(&self) -> String {
|
||||
let n = self.assets.iter().filter_map(|a| a.name.strip_prefix(ASSET)?.parse::<u64>().ok()).max().unwrap_or(0);
|
||||
let n = self
|
||||
.assets
|
||||
.iter()
|
||||
.filter_map(|a| {
|
||||
let digits = a.name.strip_prefix(ASSET)?;
|
||||
// `parse` alone would accept a leading `+`.
|
||||
digits.bytes().all(|b| b.is_ascii_digit()).then(|| digits.parse::<u64>().ok()).flatten()
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
format!("{ASSET}{}", n.saturating_add(1))
|
||||
}
|
||||
|
||||
@@ -57,3 +70,23 @@ impl Document {
|
||||
v.into_iter().map(|(_, id)| id).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn name_after(names: &[&str]) -> String {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
doc.assets.push(ExportAsset { id: i as u64 + 1, name: (*n).to_string(), nodes: vec![], format_3d: None });
|
||||
}
|
||||
doc.next_asset_name()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_asset_name_ignores_non_digit_suffixes() {
|
||||
assert_eq!(name_after(&["Asset +5"]), "Asset 1");
|
||||
assert_eq!(name_after(&["Asset ", "Asset 5x"]), "Asset 1");
|
||||
assert_eq!(name_after(&["Asset 5"]), "Asset 6");
|
||||
}
|
||||
}
|
||||
+337
-61
@@ -699,6 +699,34 @@ fn compound(path: PathData, rule: FillRule, counts: &[usize], total: usize) -> N
|
||||
/// Interpolate text `x` → `y` into `o` (a copy of the nearer): the transform by its parts, an
|
||||
/// area frame anchor by anchor, and each run's colours, stroke weight and size from the runs at
|
||||
/// the same place (by character) of both.
|
||||
/// The run of `of` at fraction `u` of its characters.
|
||||
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
|
||||
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let target = (u * total as f64) as usize;
|
||||
let mut seen = 0;
|
||||
for r in &of.runs {
|
||||
seen += r.text.chars().count();
|
||||
if seen > target {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
of.runs.last()
|
||||
}
|
||||
|
||||
/// The fraction of the characters of `runs` at the middle of each run.
|
||||
fn run_middles(runs: &[crate::text::TextRun]) -> Vec<f64> {
|
||||
let total: usize = runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
|
||||
let mut start = 0usize;
|
||||
runs.iter()
|
||||
.map(|r| {
|
||||
let len = r.text.chars().count();
|
||||
let u = (start as f64 + len as f64 / 2.0) / total as f64;
|
||||
start += len;
|
||||
u
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64) {
|
||||
o.xf = lerp_affine(x.xf, y.xf, t);
|
||||
if let (crate::text::TextKind::Area { frame: f }, crate::text::TextKind::Area { frame: fx }, crate::text::TextKind::Area { frame: fy }) =
|
||||
@@ -706,27 +734,10 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64
|
||||
{
|
||||
*f = lerp_path(fx, fy, t);
|
||||
}
|
||||
// The run of `of` at fraction `u` of its characters.
|
||||
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
|
||||
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let target = (u * total as f64) as usize;
|
||||
let mut seen = 0;
|
||||
for r in &of.runs {
|
||||
seen += r.text.chars().count();
|
||||
if seen > target {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
of.runs.last()
|
||||
}
|
||||
let total: usize = o.runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
|
||||
let mut start = 0usize;
|
||||
let tf = tc as f32;
|
||||
let mut resized = false;
|
||||
for r in &mut o.runs {
|
||||
let len = r.text.chars().count();
|
||||
let u = (start as f64 + len as f64 / 2.0) / total as f64;
|
||||
start += len;
|
||||
let middles = run_middles(&o.runs);
|
||||
for (r, u) in o.runs.iter_mut().zip(middles) {
|
||||
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
|
||||
let (sx, sy) = (&rx.style, &ry.style);
|
||||
r.style.fill = lerp_paint(&sx.fill, &sy.fill, tf);
|
||||
@@ -752,33 +763,115 @@ pub fn lerp_node(a: &Node, b: &Node, t: f64) -> Node {
|
||||
// Step counts
|
||||
// =====================================================================================
|
||||
|
||||
/// Largest channel difference (0..1) between the solid colours of two objects' top fill and stroke.
|
||||
fn color_distance(a: &Node, b: &Node) -> f32 {
|
||||
let mut d = 0.0f32;
|
||||
let mut cmp = |x: &Paint, y: &Paint| {
|
||||
let cols = |p: &Paint| -> Vec<Color> {
|
||||
match p {
|
||||
Paint::Solid { color, .. } => vec![*color],
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let (cx, cy) = (cols(x), cols(y));
|
||||
for (i, c) in cx.iter().enumerate() {
|
||||
if let Some(o) = cy.get(i).or(cy.first()) {
|
||||
let (p, q) = (c.to_rgb(), o.to_rgb());
|
||||
for k in 0..3 {
|
||||
d = d.max((p[k] - q[k]).abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Largest channel difference between two solid colors, as a fraction of the channel's range: two
|
||||
/// tints of the same swatch by their tints, RGB by its 0 to 255 values over 256, CMYK and gray by
|
||||
/// their percentages, and colors in different spaces (or Lab) by the difference of their RGB
|
||||
/// values over 255. A solid paint against no paint, or anything that isn't solid, differs by 0:
|
||||
/// [`lerp_paint`] switches such paints halfway rather than mixing them.
|
||||
fn paint_difference(x: &Paint, y: &Paint) -> f64 {
|
||||
let (Paint::Solid { color: p, swatch: sp, tint: tp }, Paint::Solid { color: q, swatch: sq, tint: tq }) = (x, y) else {
|
||||
return 0.0;
|
||||
};
|
||||
cmp(&a.appearance.fill_paint(), &b.appearance.fill_paint());
|
||||
cmp(&a.appearance.stroke_paint(), &b.appearance.stroke_paint());
|
||||
d
|
||||
if sp.is_some() && sp == sq && tp != tq {
|
||||
return f64::from((tp - tq).abs());
|
||||
}
|
||||
let most = |a: &[f32], b: &[f32]| a.iter().zip(b).fold(0.0f64, |m, (u, v)| m.max(f64::from((u - v).abs())));
|
||||
match (p, q) {
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => most(&[*r, *g, *b], &[*r2, *g2, *b2]) * 255.0 / 256.0,
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => most(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => most(&[*k], &[*k2]),
|
||||
_ => most(&p.to_rgb(), &q.to_rgb()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of intermediate steps between two keys `len` apart (along the spine).
|
||||
/// Largest difference (see [`paint_difference`]) between pairs of fills and strokes, or `None`
|
||||
/// when any of them is a gradient or a pattern.
|
||||
fn paints_difference(pairs: &[(&Paint, &Paint)]) -> Option<f64> {
|
||||
let mut d = 0.0f64;
|
||||
for (x, y) in pairs {
|
||||
if [x, y].iter().any(|p| matches!(p, Paint::Gradient(_) | Paint::Pattern { .. })) {
|
||||
return None;
|
||||
}
|
||||
d = d.max(paint_difference(x, y));
|
||||
}
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Largest channel difference (0..1, see [`paint_difference`]) between the solid colors of two
|
||||
/// keys: their top fill and stroke, the runs of two text objects paired as [`lerp_text`] pairs
|
||||
/// them, and the members of two groups paired as [`Lerp::new`] pairs them. `None` when any of
|
||||
/// these holds a gradient or a pattern, whose steps Smooth Color counts by distance.
|
||||
fn color_distance(a: &Node, b: &Node) -> Option<f64> {
|
||||
let mut d =
|
||||
paints_difference(&[(&a.appearance.fill_paint(), &b.appearance.fill_paint()), (&a.appearance.stroke_paint(), &b.appearance.stroke_paint())])?;
|
||||
match (&a.kind, &b.kind) {
|
||||
(NodeKind::Group { children: ca, clip: k1 }, NodeKind::Group { children: cb, clip: k2 }) if k1 == k2 && !(*k1 && ca.len() != cb.len()) => {
|
||||
for (x, y) in ca.iter().zip(cb) {
|
||||
d = d.max(color_distance(x, y)?);
|
||||
}
|
||||
}
|
||||
(NodeKind::Text(x), NodeKind::Text(y)) => {
|
||||
// The runs `lerp_text` pairs: those of `x` and of `y` at the middle of each run of either.
|
||||
for u in run_middles(&x.runs).into_iter().chain(run_middles(&y.runs)) {
|
||||
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
|
||||
d = d.max(paints_difference(&[(&rx.style.fill, &ry.style.fill), (&rx.style.stroke, &ry.style.stroke)])?);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
d.is_finite().then_some(d)
|
||||
}
|
||||
|
||||
/// Smooth Color's steps between two keys by distance: the largest distance between their
|
||||
/// corresponding visible bounding-box edges, in mean key widths (left and right edges) or heights
|
||||
/// (top and bottom), rounded, less one, from 1 to 1000. Keys with no width are measured in their
|
||||
/// mean height across as well, keys with no height in their mean width, and keys with neither in
|
||||
/// points.
|
||||
fn spatial_steps(ba: Rect, bb: Rect) -> usize {
|
||||
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
|
||||
let size = |s: f64, other: f64| {
|
||||
if s > 1e-9 {
|
||||
s
|
||||
} else if other > 1e-9 {
|
||||
other
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
};
|
||||
let (w, h) = (size(w, h), size(h, w));
|
||||
let q = ((ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs()) / w).max((ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs()) / h);
|
||||
if !q.is_finite() {
|
||||
return 1;
|
||||
}
|
||||
((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize
|
||||
}
|
||||
|
||||
/// `255 × d` steps for a color difference `d` (see [`color_distance`]), a half step rounding down,
|
||||
/// from 1 to 254.
|
||||
fn level_steps(d: f64) -> f64 {
|
||||
// The tolerance keeps a difference that lands on a half step (128 of 256 RGB values gives
|
||||
// 127.5), stored as an `f32`, from rounding up.
|
||||
(255.0 * d - 0.5 - 1e-4).ceil().clamp(1.0, 254.0)
|
||||
}
|
||||
|
||||
/// Smooth Color's steps between two keys whose colors differ by `d` (see [`color_distance`]):
|
||||
/// [`level_steps`], and at most eight per point of the largest of the keys' widths and heights
|
||||
/// and the distance between their centers along either axis.
|
||||
fn color_steps(d: f64, ba: Rect, bb: Rect) -> usize {
|
||||
let by_color = level_steps(d);
|
||||
let (ca, cb) = (ba.center(), bb.center());
|
||||
let reach = [(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
|
||||
let by_density = (8.0 * reach + 0.5).floor().clamp(1.0, 254.0);
|
||||
if !by_density.is_finite() {
|
||||
return by_color as usize;
|
||||
}
|
||||
by_color.min(by_density) as usize
|
||||
}
|
||||
|
||||
/// Number of intermediate steps between two keys. Specified Distance counts along the spine, `len`
|
||||
/// long between them. Smooth Color counts from the keys' colors and visible bounds, whatever the
|
||||
/// spine: keys whose colors differ make [`color_steps`] ([`level_steps`] when either key has no
|
||||
/// bounds), and others make [`spatial_steps`] (1 when either key has no bounds).
|
||||
pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) -> usize {
|
||||
match spacing {
|
||||
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
|
||||
@@ -787,17 +880,14 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
|
||||
((len / d).round() as i64 - 1).clamp(0, 1000) as usize
|
||||
}
|
||||
BlendSpacing::SmoothColor => {
|
||||
let cd = color_distance(a, b);
|
||||
if cd > 1.0 / 255.0 {
|
||||
((cd * 255.0 / 2.0).ceil() as usize).clamp(1, 256)
|
||||
} else {
|
||||
// Same colours: base the count on the distance between the objects.
|
||||
let (ba, bb) = (a.geometric_bounds(), b.geometric_bounds());
|
||||
let dist = match (ba, bb) {
|
||||
(Some(x), Some(y)) => (x.x0 - y.x0).abs().max((x.x1 - y.x1).abs()).max((x.y0 - y.y0).abs()).max((x.y1 - y.y1).abs()),
|
||||
_ => len,
|
||||
};
|
||||
((dist / 2.0).ceil() as usize).clamp(1, 256)
|
||||
let bounds = a.visual_bounds().zip(b.visual_bounds());
|
||||
match (color_distance(a, b), bounds) {
|
||||
// Colors that differ by less than a thousandth of a step count as the same.
|
||||
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => color_steps(d, ba, bb),
|
||||
(Some(d), None) if d * 255.0 > 1e-3 => level_steps(d) as usize,
|
||||
// Same colors, gradients and patterns: the distance between the objects.
|
||||
(_, Some((ba, bb))) => spatial_steps(ba, bb),
|
||||
(_, None) => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1148,13 +1238,19 @@ fn requested_steps(keys: &[Arc<Node>], spec: &BlendSpec, rail: Option<&Rail>) ->
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Most steps `spacing` makes between two keys, whatever their size and distance
|
||||
/// ([`blend_step_count`]'s clamps).
|
||||
fn most_steps(spacing: BlendSpacing) -> usize {
|
||||
/// Most steps `spacing` makes between keys `a` and `b`, whatever their size and distance
|
||||
/// ([`blend_step_count`]'s clamps). A copy of a blend is moved and scaled, never recolored
|
||||
/// ([`Shape::Other`]), so Smooth Color between colors that differ makes no more than their color
|
||||
/// change asks for, whatever the copy's scale or rotation. By distance, a copy turned by Align to
|
||||
/// Path can measure its edges differently, so it counts as up to 1000.
|
||||
fn most_steps(a: &Node, b: &Node, spacing: BlendSpacing) -> usize {
|
||||
match spacing {
|
||||
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
|
||||
BlendSpacing::Distance(_) => 1000,
|
||||
BlendSpacing::SmoothColor => 256,
|
||||
BlendSpacing::SmoothColor => match color_distance(a, b) {
|
||||
Some(d) if d * 255.0 > 1e-3 => level_steps(d) as usize,
|
||||
_ => 1000,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1182,8 +1278,8 @@ struct StepCount {
|
||||
impl StepCount {
|
||||
/// Steps the blends in `n` make in all when drawn, each keeping to [`MAX_BLEND_STEPS`].
|
||||
/// `copy`: `n` is part of a blend's step, a copy moved and scaled into place. A blend spaced
|
||||
/// by distance (or by distance where the colours match) makes more steps scaled up, so a
|
||||
/// copy counts the most its spacing can make between each pair, an upper bound for any scale.
|
||||
/// by distance, or by Smooth Color, can make more steps scaled up, so a copy counts the most
|
||||
/// its spacing can make between each pair ([`most_steps`]), an upper bound for any scale.
|
||||
fn node(&mut self, n: &Node, copy: bool) -> usize {
|
||||
let at = (std::ptr::from_ref(n) as usize, copy);
|
||||
if let Some(&known) = self.known.get(&at) {
|
||||
@@ -1249,7 +1345,11 @@ impl StepCount {
|
||||
fn most(&mut self, keys: &[Arc<Node>], spec: &BlendSpec) -> usize {
|
||||
let inside = self.nodes(keys, true);
|
||||
let each = self.steps(keys);
|
||||
let demand = each.iter().map(|&c| c.saturating_mul(most_steps(spec.spacing))).fold(0, usize::saturating_add);
|
||||
let most = keys.windows(2).map(|w| match w {
|
||||
[a, b] => most_steps(a, b, spec.spacing),
|
||||
_ => 0,
|
||||
});
|
||||
let demand = each.iter().zip(most).map(|(&c, m)| c.saturating_mul(m)).fold(0, usize::saturating_add);
|
||||
inside.saturating_add(demand.min(MAX_BLEND_STEPS.saturating_sub(inside)))
|
||||
}
|
||||
}
|
||||
@@ -1634,4 +1734,180 @@ mod tests {
|
||||
assert_eq!(blend_steps(&keys[..50], &spec), vec![1000; 49]);
|
||||
assert_eq!(fit_steps(&[10, 20], &[1, 1], MAX_BLEND_STEPS), vec![0, 0]);
|
||||
}
|
||||
|
||||
/// A key for the Smooth Color tests: a rectangle of `size` (width, height) centered on `c`,
|
||||
/// with `fill`, and `stroke` at `width`.
|
||||
fn smooth_key(c: (f64, f64), size: (f64, f64), fill: Paint, stroke: Paint, width: f64) -> Node {
|
||||
let ((cx, cy), (w, h)) = (c, size);
|
||||
let rect = Rect::new(cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0);
|
||||
Node::path(NodeId(1), shapes::rectangle(rect), Appearance::basic(fill, stroke, width))
|
||||
}
|
||||
|
||||
/// Smooth Color's steps between two filled `size` rectangles centered on `a` and `b`.
|
||||
fn smooth(a: (f64, f64), b: (f64, f64), size: (f64, f64), fill_a: Color, fill_b: Color) -> usize {
|
||||
let key = |c, fill| smooth_key(c, size, Paint::solid(fill), Paint::None, 0.0);
|
||||
blend_step_count(&key(a, fill_a), &key(b, fill_b), BlendSpacing::SmoothColor, a.0.max(b.0) - a.0.min(b.0))
|
||||
}
|
||||
|
||||
/// Smooth Color counts 255 steps for a full change of the channel that changes most, a half
|
||||
/// step rounding down: RGB values over 256, CMYK and gray in percent, a spot color by its
|
||||
/// tint, colors in different spaces by their RGB values over 255, a fill or a stroke,
|
||||
/// whichever changes more.
|
||||
#[test]
|
||||
fn smooth_color_counts_a_step_per_level_of_color_change() {
|
||||
let (a, b, size) = ((50.0, 150.0), (250.0, 150.0), (20.0, 20.0));
|
||||
let black = Color::rgb8(0, 0, 0);
|
||||
for (level, steps) in [(1, 1), (2, 2), (5, 5), (64, 64), (127, 127), (128, 127), (129, 128), (200, 199), (254, 253), (255, 254)] {
|
||||
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, 0, 0)), steps, "black to red {level}");
|
||||
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, level, level)), steps, "black to gray {level}");
|
||||
}
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)), 254);
|
||||
assert_eq!(smooth(a, b, size, black, Color::rgb8(64, 128, 0)), 127, "the channel that changes most");
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(17, 42, 93), Color::rgb8(91, 147, 220)), 127);
|
||||
for (percent, steps) in [(0.2, 1), (1.0, 3), (5.0, 13), (10.0, 25), (25.0, 64), (50.0, 127), (100.0, 254)] {
|
||||
let p = percent / 100.0;
|
||||
assert_eq!(smooth(a, b, size, Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(p, 0.0, 0.0, 0.0)), steps, "cyan {percent}%");
|
||||
assert_eq!(smooth(a, b, size, Color::gray(0.0), Color::gray(p)), steps, "gray {percent}%");
|
||||
}
|
||||
let spot = |tint: f32| Paint::Solid { color: Color::rgb8(255, 0, 0).tinted(tint), swatch: Some("Spot".into()), tint };
|
||||
let key = |c, fill| smooth_key(c, size, fill, Paint::None, 0.0);
|
||||
assert_eq!(blend_step_count(&key(a, spot(1.0)), &key(b, spot(0.5)), BlendSpacing::SmoothColor, 200.0), 127, "a tint of 50%");
|
||||
let stroked = |c, fill: Color, stroke: Color| smooth_key(c, size, Paint::solid(fill), Paint::solid(stroke), 1.0);
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
assert_eq!(blend_step_count(&stroked(a, red, black), &stroked(b, red, blue), BlendSpacing::SmoothColor, 200.0), 254, "the stroke changes");
|
||||
let outline = |c, stroke: Color| smooth_key(c, size, Paint::None, Paint::solid(stroke), 1.0);
|
||||
assert_eq!(blend_step_count(&outline(a, red), &outline(b, blue), BlendSpacing::SmoothColor, 200.0), 254, "strokes alone");
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::cmyk(0.0, 0.0, 0.0, 0.0)), 128, "RGB against CMYK white");
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::rgb8(255, 255, 255)), 127, "RGB against RGB white");
|
||||
}
|
||||
|
||||
/// Smooth Color reads the colors of group members paired in order and of text runs, and
|
||||
/// counts a solid paint against no paint by distance, since such a paint switches halfway
|
||||
/// instead of mixing.
|
||||
#[test]
|
||||
fn smooth_color_reads_the_colors_inside_groups_and_text() {
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
let square = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
|
||||
let group = |x: f64, top: Color| Node::new(NodeId(1), NodeKind::Group { children: vec![square(x, red), square(x, top)], clip: false });
|
||||
let steps = |a: &Node, b: &Node| blend_step_count(a, b, BlendSpacing::SmoothColor, 200.0);
|
||||
assert_eq!(steps(&group(50.0, red), &group(250.0, blue)), 254, "groups whose members change color");
|
||||
assert_eq!(steps(&group(50.0, red), &group(250.0, red)), 9, "groups of the same colors");
|
||||
let text = |x: f64, c: Color| {
|
||||
let style = crate::CharStyle { fill: Paint::solid(c), ..Default::default() };
|
||||
Node::new(NodeId(1), NodeKind::Text(Box::new(crate::TextObject::point(Point::new(x, 150.0), "Hi", style))))
|
||||
};
|
||||
assert_eq!(steps(&text(50.0, red), &text(250.0, blue)), 254, "text whose runs change color");
|
||||
let mut two_runs = text(250.0, red);
|
||||
if let NodeKind::Text(t) = &mut two_runs.kind {
|
||||
let style = crate::CharStyle { fill: Paint::solid(blue), ..t.runs[0].style.clone() };
|
||||
t.runs.push(crate::text::TextRun::new("Hi", style));
|
||||
}
|
||||
assert_eq!(steps(&text(50.0, red), &two_runs), 254, "a run that turns blue against one red run");
|
||||
let empty = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::None, Paint::None, 0.0);
|
||||
assert_eq!(steps(&smooth_key((50.0, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0), &empty(250.0)), 9, "a fill against none");
|
||||
let nothing = |c: Color| Node::path(NodeId(1), PathData::new(vec![]), Appearance::basic(Paint::solid(c), Paint::None, 0.0));
|
||||
assert_eq!(steps(¬hing(red), ¬hing(blue)), 254, "keys without bounds whose colors differ");
|
||||
assert_eq!(steps(¬hing(red), ¬hing(red)), 1, "keys without bounds of the same color");
|
||||
}
|
||||
|
||||
/// Smooth Color makes at most eight steps per point of the largest of the keys' widths and
|
||||
/// heights and the distance between their centers along either axis.
|
||||
#[test]
|
||||
fn smooth_color_makes_at_most_eight_steps_a_point() {
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
for (dx, steps) in [(0.0, 160), (20.0, 160), (20.1, 161), (25.0, 200), (31.5, 252), (40.0, 254)] {
|
||||
assert_eq!(smooth((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0), red, blue), steps, "{dx} pt apart");
|
||||
}
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 175.0), (20.0, 20.0), red, blue), 200, "25 pt apart vertically");
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (5.0, 5.0), red, blue), 40, "5 pt squares on each other");
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (25.0, 5.0), red, blue), 200, "the longer side counts");
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (1.0, 1.0), red, blue), 8);
|
||||
}
|
||||
|
||||
/// Smooth Color between keys of the same colors counts the largest distance between their
|
||||
/// corresponding visible edges in mean key widths or heights, rounded, less one; so do keys
|
||||
/// with gradients, whatever their colors.
|
||||
#[test]
|
||||
fn smooth_color_between_the_same_colors_counts_by_distance() {
|
||||
let red = Color::rgb8(255, 0, 0);
|
||||
let same = |a, b, size| smooth(a, b, size, red, red);
|
||||
for (dx, steps) in [(25.0, 1), (50.0, 2), (100.0, 4), (200.0, 9), (400.0, 19), (800.0, 39)] {
|
||||
assert_eq!(same((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0)), steps, "20 pt squares {dx} pt apart");
|
||||
}
|
||||
for (side, steps) in [(5.0, 39), (10.0, 19), (40.0, 4), (80.0, 2)] {
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (side, side)), steps, "{side} pt squares");
|
||||
}
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (80.0, 10.0)), 2, "wide");
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (10.0, 80.0)), 19, "tall");
|
||||
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (20.0, 20.0)), 9, "diagonal");
|
||||
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (80.0, 10.0)), 19, "wide and diagonal");
|
||||
assert_eq!(same((50.0, 150.0), (1050.0, 150.0), (1.0, 1.0)), 999);
|
||||
assert_eq!(same((50.0, 150.0), (1052.0, 150.0), (1.0, 1.0)), 1000, "at most 1000");
|
||||
assert_eq!(same((50.0, 150.0), (50.0, 150.0), (20.0, 20.0)), 1, "at least one");
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (0.0, 20.0)), 9, "vertical lines, measured in their height");
|
||||
assert_eq!(same((50.0, 150.0), (50.0, 350.0), (20.0, 0.0)), 9, "horizontal lines, measured in their width");
|
||||
assert_eq!(same((50.0, 150.0), (60.0, 150.0), (0.0, 0.0)), 9, "points, measured in points");
|
||||
let key = |c, size, stroke: f64| smooth_key(c, size, Paint::solid(red), Paint::solid(Color::BLACK), stroke);
|
||||
let wide =
|
||||
blend_step_count(&key((50.0, 150.0), (10.0, 20.0), 0.0), &key((250.0, 150.0), (80.0, 20.0), 0.0), BlendSpacing::SmoothColor, 200.0);
|
||||
assert_eq!(wide, 4, "keys of different widths");
|
||||
let strokes =
|
||||
blend_step_count(&key((50.0, 150.0), (20.0, 20.0), 1.0), &key((250.0, 150.0), (20.0, 20.0), 10.0), BlendSpacing::SmoothColor, 200.0);
|
||||
assert_eq!(strokes, 7, "strokes widen the visible edges");
|
||||
let gradient = |a: Color, b: Color| {
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
Default::default(),
|
||||
vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)],
|
||||
))))
|
||||
};
|
||||
let shaded = |c, fill| smooth_key(c, (20.0, 20.0), fill, Paint::None, 0.0);
|
||||
let blue = Color::rgb8(0, 0, 255);
|
||||
for (from, to) in [(gradient(red, blue), gradient(red, blue)), (gradient(red, blue), gradient(blue, red))] {
|
||||
assert_eq!(blend_step_count(&shaded((50.0, 150.0), from), &shaded((250.0, 150.0), to), BlendSpacing::SmoothColor, 200.0), 9);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Smooth Color blend counts each pair of keys on its own.
|
||||
#[test]
|
||||
fn smooth_color_counts_each_pair_of_keys() {
|
||||
let key = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
let spec = BlendSpec::default();
|
||||
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, red), key(250.0, blue)], &spec), vec![4, 254]);
|
||||
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, blue), key(250.0, red)], &spec), vec![254, 254]);
|
||||
}
|
||||
|
||||
/// A Smooth Color blend between different colors inside another blend's keys counts as the
|
||||
/// steps its colors ask for, so the outer blend keeps the steps it asks for within
|
||||
/// [`MAX_BLEND_STEPS`]: 200 steps, each a copy making 254 more. The copies keep their keys'
|
||||
/// colors, also halfway between a red-to-blue and a blue-to-red blend.
|
||||
#[test]
|
||||
fn a_smooth_color_blend_in_a_key_counts_its_color_steps() {
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
let key = |x: f64, c: Color| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0);
|
||||
let inner = |x: f64, from: Color, to: Color| blend_of(key(x, from), key(x + 100.0, to), BlendSpacing::SmoothColor);
|
||||
let outer = blend_of(inner(0.0, red, blue), inner(500.0, red, blue), BlendSpacing::Steps(200));
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![200]);
|
||||
let crossed = blend_of(inner(0.0, red, blue), inner(500.0, blue, red), BlendSpacing::Steps(199));
|
||||
let (keys, spec) = blend_parts(&crossed).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![199]);
|
||||
let drawn = blend_expand(keys, spec);
|
||||
let Some(NodeKind::Blend { children, .. }) = drawn.get(100).map(|n| &n.kind) else { panic!("a copy of a blend halfway") };
|
||||
let fills: Vec<_> = children.iter().map(|k| k.appearance.fill_paint().color()).collect();
|
||||
assert!(fills == [Some(red), Some(blue)] || fills == [Some(blue), Some(red)], "{fills:?}");
|
||||
}
|
||||
|
||||
/// A Smooth Color blend between the same colors inside another blend's keys counts as up to
|
||||
/// 1000 steps, which a copy turned to a path can ask for: 200 steps of copies of it come
|
||||
/// down to 99.
|
||||
#[test]
|
||||
fn a_smooth_color_blend_of_the_same_colors_in_a_key_counts_up_to_1000_steps() {
|
||||
let red = Color::rgb8(255, 0, 0);
|
||||
let key = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0);
|
||||
let inner = |x: f64| blend_of(key(x), key(x + 100.0), BlendSpacing::SmoothColor);
|
||||
let outer = blend_of(inner(0.0), inner(500.0), BlendSpacing::Steps(200));
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![99]);
|
||||
}
|
||||
}
|
||||
@@ -313,8 +313,8 @@ mod tests {
|
||||
d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into();
|
||||
d.assets = vec![
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)] },
|
||||
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)] },
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None },
|
||||
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)], format_3d: None },
|
||||
];
|
||||
d.variables.bindings.insert(NodeId(11), ["v".to_string()].into());
|
||||
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
|
||||
|
||||
@@ -68,6 +68,7 @@ impl Document {
|
||||
print_setup,
|
||||
assets,
|
||||
svg_scripts,
|
||||
svg_filters,
|
||||
puppet,
|
||||
new_art,
|
||||
dimensions,
|
||||
@@ -135,6 +136,7 @@ impl Document {
|
||||
&& *print_setup == other.print_setup
|
||||
&& *assets == other.assets
|
||||
&& *svg_scripts == other.svg_scripts
|
||||
&& *svg_filters == other.svg_filters
|
||||
&& match (puppet, &other.puppet) {
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
@@ -245,6 +247,7 @@ impl Document {
|
||||
print_setup: None,
|
||||
assets: vec![],
|
||||
svg_scripts: vec![],
|
||||
svg_filters: vec![],
|
||||
puppet: None,
|
||||
new_art: Default::default(),
|
||||
dimensions: false,
|
||||
@@ -352,6 +355,7 @@ impl Document {
|
||||
}
|
||||
false
|
||||
}
|
||||
crate::id_index::note_tree_walk();
|
||||
let mut p = vec![];
|
||||
find(&self.layers, id, &mut p).then_some(p)
|
||||
}
|
||||
@@ -393,6 +397,7 @@ impl Document {
|
||||
});
|
||||
}
|
||||
if !want.is_empty() {
|
||||
crate::id_index::note_tree_walk();
|
||||
let mut rest = HashMap::with_capacity(want.len());
|
||||
walk(&self.layers, &want, &mut Vec::new(), &mut rest);
|
||||
out.extend(rest);
|
||||
|
||||
@@ -123,6 +123,39 @@ impl Document {
|
||||
std::borrow::Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// Does `wants` hold for a node anywhere in the document's art: the layers, symbol definitions,
|
||||
/// graph designs, pattern swatches (the one being edited included) and their opacity masks?
|
||||
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
|
||||
let roots = self
|
||||
.layers
|
||||
.iter()
|
||||
.chain(self.symbols.iter().map(|s| &s.art))
|
||||
.chain(self.graph_designs.iter().map(|g| &g.art))
|
||||
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
|
||||
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()));
|
||||
let mut any = false;
|
||||
for root in roots {
|
||||
crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n));
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// Change with `f` every node for which `wants` holds, anywhere in the document's art (as
|
||||
/// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art
|
||||
/// they share.
|
||||
pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) {
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
edit_branches_where(root, &wants, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Round every path's anchors and handles to `decimals` decimal places: path objects (with
|
||||
/// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine
|
||||
/// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being
|
||||
@@ -164,7 +197,7 @@ impl Document {
|
||||
}
|
||||
}
|
||||
NodeKind::Envelope { kind, .. } => {
|
||||
if let EnvelopeKind::TopObject { path } = kind.as_mut() {
|
||||
if let EnvelopeKind::TopObject { path, .. } = kind.as_mut() {
|
||||
round_path(path);
|
||||
}
|
||||
}
|
||||
@@ -194,6 +227,26 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
|
||||
/// copying out of the shared art only the branches that hold one.
|
||||
fn edit_branches_where(n: &mut Arc<Node>, wants: &impl Fn(&Node) -> bool, f: &mut impl FnMut(&mut Node)) {
|
||||
let mut any = false;
|
||||
crate::swatches::walk_with_masks(n, &mut |c| any |= wants(c));
|
||||
if !any {
|
||||
return;
|
||||
}
|
||||
let node = Arc::make_mut(n);
|
||||
if wants(node) {
|
||||
f(node);
|
||||
}
|
||||
if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
edit_branches_where(&mut m.art, wants, f);
|
||||
}
|
||||
for c in node.children_mut().into_iter().flatten() {
|
||||
edit_branches_where(c, wants, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every
|
||||
/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as
|
||||
/// [`Document::round_geometry`] rounds the nodes it holds.
|
||||
|
||||
@@ -936,6 +936,257 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
/// The art of a symbol instance with its own appearance changes, in the symbol's coordinates, and
|
||||
/// how the canvas places each object of it: through the symbol's 9-slice guides when the instance
|
||||
/// is scaled by them ([`Document::place_symbol_art`]), otherwise by the instance's transform.
|
||||
struct InstanceArt {
|
||||
art: Node,
|
||||
map: Option<crate::NineSliceMap>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
}
|
||||
|
||||
impl InstanceArt {
|
||||
/// The art of symbol instance `inst`. `None` for anything else, a missing symbol, or art that
|
||||
/// placing through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of,
|
||||
/// which [`Document::place_symbol_art`] does not place and the canvas does not draw.
|
||||
fn of(doc: &Document, inst: &Node) -> Option<Self> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = crate::symbol_overrides::dynamic_art(&sym.art, inst);
|
||||
let map = doc.symbol_slice_map(symbol, *xf);
|
||||
if map.as_ref().is_some_and(|m| m.most_placed(&art, doc) > crate::MAX_SYMBOL_NODES) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { art, map, xf: *xf })
|
||||
}
|
||||
|
||||
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
|
||||
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
|
||||
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
|
||||
/// object by object.
|
||||
fn whole(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
|
||||
whole.or_else(|| self.map.as_ref()?.one_cell(n, doc))
|
||||
}
|
||||
|
||||
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
|
||||
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
|
||||
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
|
||||
/// [`Document::place_symbol_art`] refuses it.
|
||||
fn place(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
|
||||
match (&self.map, whole) {
|
||||
(_, Some(a)) => Some(moved(n, a)),
|
||||
(Some(m), None) => (m.most_placed(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place(n, doc)),
|
||||
(None, None) => Some(moved(n, self.xf)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Object `n` of the art placed on the canvas without clip groups
|
||||
/// ([`crate::NineSliceMap::place_unclipped`]), as [`Self::place`] places it and within the
|
||||
/// same limit ([`Document::place_symbol_art_unclipped`]).
|
||||
fn place_unclipped(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
|
||||
match (&self.map, whole) {
|
||||
(_, Some(a)) => Some(moved(n, a)),
|
||||
(Some(m), None) => (m.most_placed_unclipped(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place_unclipped(n, doc)),
|
||||
(None, None) => Some(moved(n, self.xf)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` transformed by `xf`, its strokes at their own weight.
|
||||
fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
let mut out = n.clone();
|
||||
out.transform(xf, false);
|
||||
out
|
||||
}
|
||||
|
||||
/// The object of symbol instance `inst`'s art under `p`, for Direct Selection on a dynamic symbol's
|
||||
/// instance: its path of child indices from the art's root ([`crate::symbol_overrides::part`]), the
|
||||
/// topmost object hit inside the art's groups. With [`HitOptions::clip_outlines`], a press on the
|
||||
/// outline of the clipping path of a clip group or a clipping layer picks that path before the art
|
||||
/// it clips, as [`hit_test`] does outside symbols. Hidden, locked and template objects are passed
|
||||
/// over, as [`hit_test`] passes over them when it looks for editable objects, and so are a Shaper
|
||||
/// group's original shapes, which the canvas does not draw, and guide paths with
|
||||
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
|
||||
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
|
||||
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
struct Find<'a> {
|
||||
doc: &'a Document,
|
||||
art: &'a InstanceArt,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
}
|
||||
impl Find<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
|
||||
}
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
|
||||
return false;
|
||||
}
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole);
|
||||
}
|
||||
let whole = self.art.whole(n, self.doc, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false };
|
||||
if self.opt.clip_outlines
|
||||
&& first.visible
|
||||
&& !first.locked
|
||||
&& !self.skips_guide(first)
|
||||
&& clip_outline(&clip, self.p, self.opt).is_some()
|
||||
{
|
||||
path.push(0);
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(&clip, self.p) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
|
||||
if shaper_hides(n, i, None) {
|
||||
continue;
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if self.find(c, path, whole) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
|
||||
}
|
||||
|
||||
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
|
||||
/// placed on the canvas as it is drawn: its paths' outlines, and the bounds of objects without a
|
||||
/// path. Inside a clip group (an object drawn once in each 9-slice cell it reaches is one clip
|
||||
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
|
||||
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
|
||||
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
|
||||
/// picks it.
|
||||
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
|
||||
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let part = crate::symbol_overrides::part(&art.art, path)?;
|
||||
let mut out = BezPath::new();
|
||||
let mut limit = None;
|
||||
let mut whole = None;
|
||||
let mut n = &art.art;
|
||||
for &i in path {
|
||||
let children = n.children()?;
|
||||
whole = art.whole(n, doc, whole);
|
||||
if i != 0
|
||||
&& n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
&& let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds()
|
||||
{
|
||||
match meet(Some(clip), limit) {
|
||||
Some(r) => limit = Some(r),
|
||||
None => return Some(out),
|
||||
}
|
||||
}
|
||||
n = children.get(usize::try_from(i).ok()?)?;
|
||||
}
|
||||
outline_within(&art.place(part, doc, whole)?, limit, &mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
if let Some(pd) = n.path_data() {
|
||||
match limit {
|
||||
Some(r) => push_cut(out, &pd.to_bezpath(), r),
|
||||
None => out.extend(pd.to_bezpath()),
|
||||
}
|
||||
} else if n.children().is_none()
|
||||
&& let Some(b) = n.geometric_bounds()
|
||||
&& let Some(b) = meet(Some(b), limit)
|
||||
{
|
||||
out.extend(b.to_path(0.1));
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
if n.clips()
|
||||
&& let Some((first, rest)) = children.split_first()
|
||||
{
|
||||
let inner = match first.geometric_bounds() {
|
||||
Some(c) => match meet(Some(c), limit) {
|
||||
Some(r) => Some(r),
|
||||
None => return,
|
||||
},
|
||||
None => limit,
|
||||
};
|
||||
rest.iter().for_each(|c| outline_within(c, inner, out));
|
||||
return;
|
||||
}
|
||||
children.iter().for_each(|c| outline_within(c, limit, out));
|
||||
}
|
||||
|
||||
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
|
||||
fn meet(a: Option<Rect>, b: Option<Rect>) -> Option<Rect> {
|
||||
let a = a?;
|
||||
let Some(b) = b else { return Some(a) };
|
||||
let r = Rect::new(a.x0.max(b.x0), a.y0.max(b.y0), a.x1.min(b.x1), a.y1.min(b.y1));
|
||||
(r.x0 <= r.x1 && r.y0 <= r.y1).then_some(r)
|
||||
}
|
||||
|
||||
/// The parts of path `p`, flattened to lines, that lie inside `r`, appended to `out`.
|
||||
fn push_cut(out: &mut BezPath, p: &BezPath, r: Rect) {
|
||||
use vectorcraft_geom::kurbo::PathEl;
|
||||
let (mut at, mut start, mut last) = (Point::ZERO, Point::ZERO, None::<Point>);
|
||||
vectorcraft_geom::kurbo::flatten(p.iter(), 0.1, |el| {
|
||||
let to = match el {
|
||||
PathEl::MoveTo(q) => {
|
||||
(at, start, last) = (q, q, None);
|
||||
return;
|
||||
}
|
||||
PathEl::LineTo(q) => q,
|
||||
PathEl::ClosePath => start,
|
||||
_ => return,
|
||||
};
|
||||
if let Some((a, b)) = cut_segment(at, to, r) {
|
||||
if last != Some(a) {
|
||||
out.move_to(a);
|
||||
}
|
||||
out.line_to(b);
|
||||
last = Some(b);
|
||||
}
|
||||
at = to;
|
||||
});
|
||||
}
|
||||
|
||||
/// The part of segment `a` to `b` inside `r`, `None` when none of it is.
|
||||
fn cut_segment(a: Point, b: Point, r: Rect) -> Option<(Point, Point)> {
|
||||
let d = b - a;
|
||||
let (mut t0, mut t1) = (0.0_f64, 1.0_f64);
|
||||
for (p, q) in [(-d.x, a.x - r.x0), (d.x, r.x1 - a.x), (-d.y, a.y - r.y0), (d.y, r.y1 - a.y)] {
|
||||
if p.abs() < 1e-12 {
|
||||
if q < 0.0 {
|
||||
return None;
|
||||
}
|
||||
} else if p < 0.0 {
|
||||
t0 = t0.max(q / p);
|
||||
} else {
|
||||
t1 = t1.min(q / p);
|
||||
}
|
||||
}
|
||||
(t0 <= t1).then(|| (a + d * t0, a + d * t1))
|
||||
}
|
||||
|
||||
/// The path of compound path `n` under `p`, for the Group Selection tool: the one whose outline is
|
||||
/// within `tol`, else the innermost one whose area holds `p` (a hole inside an outer shape, an
|
||||
/// island inside a hole). `None` when `n` isn't a compound path or no part is under `p`.
|
||||
|
||||
@@ -1373,3 +1373,128 @@ fn cull_box_holds_the_reach_of_paths_and_compound_paths() {
|
||||
assert!(holds(cull, reach), "{cull:?} does not hold {reach:?}");
|
||||
assert_eq!(checked, 201);
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art, a layer with a clipping mask clips its objects as a clip group does:
|
||||
/// Direct Selection picks an object only where the mask shows it, and outlines it there.
|
||||
#[test]
|
||||
fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
|
||||
if let NodeKind::Layer { children, .. } = &mut layer.kind {
|
||||
*children = vec![Arc::new(mask), Arc::new(art)];
|
||||
}
|
||||
layer.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "where the mask shows the art");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), None, "where the mask hides it");
|
||||
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[0, 1]).unwrap());
|
||||
assert!((b.x1 - 100.0).abs() < 1e-6, "the outline is cut to the mask: {b:?}");
|
||||
// Its outline inside the group around the layer is cut too.
|
||||
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[0]).unwrap());
|
||||
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
#[test]
|
||||
fn symbol_art_past_the_object_limit_picks_nothing() {
|
||||
use vectorcraft_color::{Gradient, GradientPaint};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let leaf = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
|
||||
let inner = Arc::new(Node::group(d.alloc_id(), vec![leaf; 1_800]));
|
||||
let mut mask = crate::OpacityMask::new(Node::group(d.alloc_id(), vec![inner; 1_800]), true);
|
||||
mask.linked = false;
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
// Drawn in six cells, each with its own copy of the mask's 3,240,000 squares.
|
||||
let mut big = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
big.extras_mut().mask = Some(Box::new(mask));
|
||||
let plain = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 50.0, 100.0, 100.0)), Appearance::default_art());
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(plain), Arc::new(big)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Big".into(), art: Arc::new(root) });
|
||||
d.set_symbol_nine_slice("Big", Some(crate::SymbolNineSlice::default()));
|
||||
let scaled = d.alloc_id();
|
||||
let natural = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
|
||||
d.insert(Some(l), 0, Node::new(scaled, NodeKind::SymbolInstance { symbol: "Big".into(), xf })).unwrap();
|
||||
d.insert(Some(l), 0, Node::new(natural, NodeKind::SymbolInstance { symbol: "Big".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
assert!(d.place_symbol_art("Big", &d.symbols[0].art, xf).is_none(), "the art is past the limit");
|
||||
let opt = HitOptions::default();
|
||||
let n = d.node(scaled).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(100.0, 110.0), opt), None, "the plain square");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(100.0, 40.0), opt), None, "the masked path");
|
||||
assert!(symbol_part_outline(&d, n, &[0]).is_none());
|
||||
assert!(symbol_part_outline(&d, n, &[1]).is_none());
|
||||
let n = d.node(natural).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 75.0), opt), Some(vec![0]));
|
||||
assert!(symbol_part_outline(&d, n, &[0]).is_some());
|
||||
}
|
||||
|
||||
/// A clip group that lies in one 9-slice cell is moved by that cell as one piece, everything in it
|
||||
/// included, so an object in it is picked and outlined there even when placing that object through
|
||||
/// the guides on its own would pass [`crate::MAX_SYMBOL_NODES`] objects.
|
||||
#[test]
|
||||
fn objects_of_a_clip_group_in_one_cell_are_placed_with_it() {
|
||||
use vectorcraft_color::{Gradient, GradientPaint};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let leaf = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
|
||||
let inner = Arc::new(Node::group(d.alloc_id(), vec![leaf; 1_800]));
|
||||
let mut mask = crate::OpacityMask::new(Node::group(d.alloc_id(), vec![inner; 1_800]), true);
|
||||
mask.linked = false;
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
let mut big = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
big.extras_mut().mask = Some(Box::new(mask));
|
||||
let clip = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(big.clone())]);
|
||||
group.set_clips(true);
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(group)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Corner".into(), art: Arc::new(root) });
|
||||
d.set_symbol_nine_slice("Corner", Some(crate::SymbolNineSlice::default()));
|
||||
let inst = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corner".into(), xf })).unwrap();
|
||||
let m = d.symbol_slice_map("Corner", xf).unwrap();
|
||||
assert!(m.most_placed(&big, &d) > crate::MAX_SYMBOL_NODES, "the object alone is past the limit");
|
||||
assert!(d.place_symbol_art("Corner", &d.symbols[0].art, xf).is_some(), "the art is drawn");
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(10.0, 10.0), HitOptions::default()), Some(vec![1, 1]));
|
||||
let b = vectorcraft_geom::kurbo::Shape::bounding_box(&symbol_part_outline(&d, n, &[1, 1]).unwrap());
|
||||
assert!((b.x1 - 20.0).abs() < 1e-6 && (b.y1 - 20.0).abs() < 1e-6, "cut to the clip in its corner: {b:?}");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art, Direct Selection does not pick a Shaper group's original shapes,
|
||||
/// which the canvas does not draw: a click over an original shape whose face the group erased
|
||||
/// picks nothing, and a click over the face it shows picks the face.
|
||||
#[test]
|
||||
fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0));
|
||||
let a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
let b = Node::path(d.alloc_id(), square(50.0), Appearance::default_art());
|
||||
let mut sources = Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]);
|
||||
sources.name = Some(crate::shaper::SOURCES.into());
|
||||
sources.opacity = 0.0;
|
||||
let mut face = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
face.name = Some(format!("{}0", crate::shaper::FILL_PREFIX));
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(sources), Arc::new(face)]);
|
||||
group.extras_mut().shaper = Some(Box::default());
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(group)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Shaped".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Shaped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
|
||||
}
|
||||
@@ -90,6 +90,24 @@ impl Paths {
|
||||
/// object and look the next one up, again and again).
|
||||
const MISSES_PER_REBUILD: u32 = 4;
|
||||
|
||||
thread_local! {
|
||||
/// [`tree_walks`] of this thread.
|
||||
static TREE_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times lookups by id on this thread have walked a document's tree, reading up to all of
|
||||
/// its nodes: one count per search of the tree and per rebuild of the cache. An edit that looks its
|
||||
/// objects up one at a time counts about one walk per object; one that looks them all up at once
|
||||
/// counts a few.
|
||||
pub fn tree_walks() -> u64 {
|
||||
TREE_WALKS.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`tree_walks`].
|
||||
pub(crate) fn note_tree_walk() {
|
||||
TREE_WALKS.set(TREE_WALKS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree).
|
||||
#[derive(Default)]
|
||||
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32);
|
||||
@@ -125,6 +143,7 @@ impl IdIndex {
|
||||
}
|
||||
}
|
||||
}
|
||||
note_tree_walk();
|
||||
let mut out = Paths::default();
|
||||
walk(layers, u32::MAX, &mut out);
|
||||
let out = Arc::new(out);
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub use id_index::tree_walks;
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub mod intertwine;
|
||||
@@ -108,7 +109,7 @@ pub use placed_document::{PageBox, PlacedDocument};
|
||||
pub use profiles::ColorProfiles;
|
||||
pub use puppet::{PuppetPin, PuppetPins};
|
||||
pub use rastersettings::{RasterColorModel, RasterEffectsSettings};
|
||||
pub use selection::{AnchorRef, SegmentRef, Selection};
|
||||
pub use selection::{AnchorRef, SegmentRef, Selection, SymbolPart};
|
||||
pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
|
||||
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
|
||||
pub use style_libs::StyleLibrary;
|
||||
@@ -140,7 +141,7 @@ mod limits;
|
||||
mod records;
|
||||
mod units;
|
||||
|
||||
pub use artboard::{Artboard, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
pub use canvas_range::BeyondCanvas;
|
||||
#[cfg(test)]
|
||||
use document_ext::free_id;
|
||||
@@ -149,7 +150,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
|
||||
#[cfg(test)]
|
||||
use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol, SymbolEdit};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use units::{ColorMode, Unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -309,6 +310,10 @@ pub struct Document {
|
||||
/// given) SVG export links with `<script>` elements, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub svg_scripts: Vec<String>,
|
||||
/// Effect › SVG Filters: the SVG filters the document holds (at most [`SvgFilter::MAX`]), in
|
||||
/// the order the submenu lists them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub svg_filters: Vec<SvgFilter>,
|
||||
/// Puppet Warp pins on the selected artwork while the tool edits it ([`PuppetPins`]): editing
|
||||
/// state, never saved.
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -415,6 +415,68 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::update_links`] for the links `pick` holds for only, in one pass; only the nodes on the
|
||||
/// way to one are copied.
|
||||
pub fn update_links_where(&mut self, pick: impl Fn(&LinkInfo) -> bool, mut f: impl FnMut(&mut LinkInfo)) {
|
||||
fn link_of(n: &Node) -> Option<&LinkInfo> {
|
||||
match &n.kind {
|
||||
NodeKind::Image(image) => image.link.as_ref(),
|
||||
NodeKind::PlacedDocument(placed) => Some(&placed.link),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `n` updated in place, a copy of it when shared; left as it is when it holds no picked link.
|
||||
fn update(n: &mut Arc<Node>, pick: &dyn Fn(&LinkInfo) -> bool, f: &mut dyn FnMut(&mut LinkInfo)) {
|
||||
// Each child is updated through a second handle, so an updated child is a new node and a new
|
||||
// pointer marks a change.
|
||||
let mask = n.extras().mask.as_ref().and_then(|m| {
|
||||
let mut art = Arc::clone(&m.art);
|
||||
update(&mut art, pick, f);
|
||||
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
|
||||
});
|
||||
let mut children = vec![];
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
let mut new = Arc::clone(c);
|
||||
update(&mut new, pick, f);
|
||||
if !Arc::ptr_eq(&new, c) {
|
||||
children.push((i, new));
|
||||
}
|
||||
}
|
||||
let own = link_of(n).is_some_and(pick);
|
||||
if !own && mask.is_none() && children.is_empty() {
|
||||
return;
|
||||
}
|
||||
let n = Arc::make_mut(n);
|
||||
let link = match &mut n.kind {
|
||||
NodeKind::Image(image) => image.link.as_mut(),
|
||||
NodeKind::PlacedDocument(placed) => Some(&mut placed.link),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(link) = link.filter(|_| own) {
|
||||
f(link);
|
||||
}
|
||||
if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) {
|
||||
m.art = art;
|
||||
}
|
||||
if let Some(slots) = n.children_mut() {
|
||||
for (i, c) in children {
|
||||
if let Some(slot) = slots.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
|
||||
for root in roots {
|
||||
update(root, &pick, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Change every image object (in the layers, symbol definitions and pattern swatches, opacity-mask
|
||||
/// art included) for which `pick` holds; only the subtrees holding one are copied.
|
||||
pub fn update_images(&mut self, pick: impl Fn(&ImageObject) -> bool, mut f: impl FnMut(&mut ImageObject)) {
|
||||
@@ -486,6 +548,40 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// `update_links_where` changes only the picked links, in a copy of the nodes on the way to them;
|
||||
/// the other nodes stay shared with the document it was cloned from.
|
||||
#[test]
|
||||
fn update_links_where_copies_only_the_nodes_it_changes() {
|
||||
let mut d = Document::new(10.0, 10.0);
|
||||
image(&mut d, "a", Some(LinkInfo::new("/art/a.png")));
|
||||
image(&mut d, "b", Some(LinkInfo::new("/art/b.png")));
|
||||
image(&mut d, "c", None);
|
||||
let mut copy = d.clone();
|
||||
let mut calls = 0;
|
||||
copy.update_links_where(
|
||||
|l| l.path == "/art/a.png",
|
||||
|l| {
|
||||
calls += 1;
|
||||
l.relative = Some("art/a.png".into());
|
||||
},
|
||||
);
|
||||
assert_eq!(calls, 1);
|
||||
let node = |d: &Document, key: &str| {
|
||||
d.layers[0].children().unwrap().iter().find(|n| matches!(&n.kind, NodeKind::Image(im) if im.key == key)).unwrap().clone()
|
||||
};
|
||||
let relative = |n: &Node| match &n.kind {
|
||||
NodeKind::Image(im) => im.link.as_ref().and_then(|l| l.relative.clone()),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!((relative(&node(©, "a")), relative(&node(&d, "a"))), (Some("art/a.png".into()), None));
|
||||
assert!(Arc::ptr_eq(&node(©, "b"), &node(&d, "b")) && Arc::ptr_eq(&node(©, "c"), &node(&d, "c")));
|
||||
assert!(!Arc::ptr_eq(©.layers[0], &d.layers[0]));
|
||||
// Nothing picked: nothing is copied.
|
||||
let mut same = d.clone();
|
||||
same.update_links_where(|_| false, |_| {});
|
||||
assert!(Arc::ptr_eq(&same.layers[0], &d.layers[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_placeholder_is_a_png() {
|
||||
let png = missing_placeholder().unwrap();
|
||||
|
||||
+300
-2
@@ -53,8 +53,9 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
|
||||
#[cfg(test)]
|
||||
use blend_spec::{blend_color_shift, blend_ramp};
|
||||
pub use envelope::{
|
||||
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, envelope_bounds, envelope_content_boxes,
|
||||
envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin, smooth_handles,
|
||||
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
|
||||
envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin,
|
||||
set_type_ink, smooth_handles,
|
||||
};
|
||||
pub(crate) use expand::max_outset;
|
||||
pub use expand::{
|
||||
@@ -173,6 +174,303 @@ mod tests {
|
||||
assert!((c.x - 105.0).abs() < 1e-6 && (c.y + 10.0).abs() < 1e-6, "{c:?}");
|
||||
}
|
||||
|
||||
/// A 100 × 50 outline whose top side runs (0,0) → (30,0) → (100,0) as two straight segments.
|
||||
fn top_split_at_30() -> PathData {
|
||||
let a = |x: f64, y: f64| Anchor::corner(Point::new(x, y));
|
||||
PathData::single(SubPath::new(vec![a(0.0, 0.0), a(30.0, 0.0), a(100.0, 0.0), a(100.0, 50.0), a(0.0, 50.0)], true))
|
||||
}
|
||||
|
||||
/// The length of `c`'s control polygon.
|
||||
fn polygon(c: CubicBez) -> f64 {
|
||||
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
|
||||
}
|
||||
|
||||
/// An anchor and its incoming and outgoing handles.
|
||||
type Knot = ((f64, f64), (f64, f64), (f64, f64));
|
||||
|
||||
/// A closed path through `pts`.
|
||||
fn outline(pts: &[Knot]) -> PathData {
|
||||
let a = |&(p, i, o): &Knot| Anchor { p: p.into(), h_in: i.into(), h_out: o.into(), ..Anchor::corner(p.into()) };
|
||||
PathData::single(SubPath::new(pts.iter().map(a).collect(), true))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_of_straight_segments_spreads_by_length() {
|
||||
// The top side runs (0,0) → (30,0) → (100,0): each straight piece takes its length's share.
|
||||
let kind = EnvelopeKind::TopObject { path: top_split_at_30(), corners: None };
|
||||
let map = envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 50.0));
|
||||
for (q, want) in [((50.0, 0.0), (50.0, 0.0)), ((15.0, 0.0), (15.0, 0.0)), ((80.0, 0.0), (80.0, 0.0)), ((50.0, 25.0), (50.0, 25.0))] {
|
||||
let p = map(Point::new(q.0, q.1));
|
||||
assert!(p.distance(Point::new(want.0, want.1)) < 1e-6, "{q:?} → {p:?}, want {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_shares_a_side_by_control_polygon_length() {
|
||||
// Two curves of unequal polygons make the top side; the anchor between them lands at the
|
||||
// first one's share, and inside each curve the content follows its parameter.
|
||||
let first = CubicBez::new((0.0, 0.0), (10.0, -20.0), (30.0, -20.0), (40.0, 0.0));
|
||||
let second = CubicBez::new((40.0, 0.0), (60.0, 10.0), (90.0, 10.0), (100.0, 0.0));
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), (10.0, -20.0)),
|
||||
((40.0, 0.0), (30.0, -20.0), (60.0, 10.0)),
|
||||
((100.0, 0.0), (90.0, 10.0), (100.0, 0.0)),
|
||||
((100.0, 80.0), (100.0, 80.0), (100.0, 80.0)),
|
||||
((0.0, 80.0), (0.0, 80.0), (0.0, 80.0)),
|
||||
]);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
let share = polygon(first) / (polygon(first) + polygon(second));
|
||||
assert!(c.eval(share, 0.0).distance(Point::new(40.0, 0.0)) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
for f in [0.25, 0.5, 0.75] {
|
||||
let p = c.eval(share * f, 0.0);
|
||||
assert!(p.distance(first.eval(f)) < 1e-9, "first curve at {f}: {p:?}");
|
||||
let p = c.eval(share + (1.0 - share) * f, 0.0);
|
||||
assert!(p.distance(second.eval(f)) < 1e-9, "second curve at {f}: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_rectangle_top_object_stays_close_to_the_identity() {
|
||||
// The corners fall at the middle of each corner arc. Each half arc takes the share of its
|
||||
// control polygon, so the straight edges stay close to where the content was.
|
||||
let r = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let path = shapes::rounded_rectangle(r, 10.0);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
let [tl, tr, br, bl] = c.corners();
|
||||
let k = 10.0 * (1.0 - std::f64::consts::FRAC_1_SQRT_2);
|
||||
for (p, want) in [(tl, (k, k)), (tr, (200.0 - k, k)), (br, (200.0 - k, 100.0 - k)), (bl, (k, 100.0 - k))] {
|
||||
assert!(p.distance(Point::from(want)) < 0.01, "corner {p:?}, want {want:?}");
|
||||
}
|
||||
for (u, v) in [(0.25, 0.0), (0.5, 0.0), (0.8, 1.0), (0.0, 0.5), (0.5, 0.5), (1.0, 0.3)] {
|
||||
let p = c.eval(u, v);
|
||||
assert!(p.distance(Point::new(200.0 * u, 100.0 * v)) < 3.0, "({u}, {v}) → {p:?}");
|
||||
}
|
||||
// The top edge starts after the first half arc's share.
|
||||
let sp = &path.subpaths[0];
|
||||
let edge = Point::new(10.0, 0.0);
|
||||
let arc = (0..sp.segment_count())
|
||||
.filter(|i| !sp.segment_is_line(*i))
|
||||
.map(|i| sp.segment(i))
|
||||
.find(|s| s.p0.distance(edge) < 1e-9 || s.p3.distance(edge) < 1e-9)
|
||||
.unwrap();
|
||||
let half = polygon(if arc.p3.distance(edge) < 1e-9 { arc.subsegment(0.5..1.0) } else { arc.subsegment(0.0..0.5) });
|
||||
let p = c.eval(half / (2.0 * half + 180.0), 0.0);
|
||||
assert!(p.distance(Point::new(10.0, 0.0)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_inside_a_bulging_curve_is_the_nearest_outline_point() {
|
||||
// The top left anchor's handle bulges out past the corner, so the anchor turns inward
|
||||
// there and the corner falls inside the curve.
|
||||
// The outline's bounding box starts at (-7.957, -22.222); the top curve's point nearest
|
||||
// that corner, found by sampling the curve 2,000,000 times, is (-5.072093, -18.127254).
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), (-50.0, -50.0)),
|
||||
((200.0, 0.0), (150.0, 0.0), (200.0, 0.0)),
|
||||
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
|
||||
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
|
||||
]);
|
||||
let want = Point::new(-5.072093, -18.127254);
|
||||
let tl = Coons::from_top_object(&path, None).unwrap().corners()[0];
|
||||
assert!(tl.distance(want) < 1e-5, "{tl:?}, want {want:?}");
|
||||
assert!(tl.distance(Point::ZERO) > 1.0, "{tl:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_takes_an_anchor_only_near_its_box_corner() {
|
||||
// A chamfered top left corner of a 200 × 100 outline. With both chamfer anchors within
|
||||
// 47.5% of the box from its corner, the nearer anchor is the corner.
|
||||
let chamfer = |a: (f64, f64), b: (f64, f64)| {
|
||||
let c = |p: (f64, f64)| (p, p, p);
|
||||
outline(&[c(a), c(b), c((200.0, 0.0)), c((200.0, 100.0)), c((0.0, 100.0))])
|
||||
};
|
||||
let tl = Coons::from_top_object(&chamfer((0.0, 46.0), (94.0, 0.0)), None).unwrap().corners()[0];
|
||||
assert!(tl.distance(Point::new(0.0, 46.0)) < 1e-9, "{tl:?}");
|
||||
// Farther out, neither anchor counts: the corner is the chamfer's point nearest the box corner.
|
||||
let tl = Coons::from_top_object(&chamfer((0.0, 50.0), (100.0, 0.0)), None).unwrap().corners()[0];
|
||||
assert!(tl.distance(Point::new(20.0, 40.0)) < 1e-6, "{tl:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_skips_smooth_and_inward_anchors() {
|
||||
// A top left anchor whose outgoing handle turns from its incoming one by `deg` degrees
|
||||
// (positive turns out of the outline). The top side bulges up past it.
|
||||
let shape = |deg: f64| {
|
||||
let a = deg.to_radians();
|
||||
let (hx, hy) = (50.0 * a.cos() + 40.0 * a.sin(), 40.0 * a.cos() - 50.0 * a.sin());
|
||||
outline(&[
|
||||
((50.0, -300.0), (25.0, -280.0), (50.0 + hx, -300.0 - hy)),
|
||||
((250.0, -300.0), (200.0, -340.0), (250.0, -300.0)),
|
||||
((250.0, -200.0), (250.0, -200.0), (250.0, -200.0)),
|
||||
((50.0, -200.0), (50.0, -200.0), (50.0, -230.0)),
|
||||
])
|
||||
};
|
||||
let corner = |deg: f64| Coons::from_top_object(&shape(deg), None).unwrap().corners()[0];
|
||||
let anchor = Point::new(50.0, -300.0);
|
||||
for deg in [0.0, 0.4, 0.6, -1.5] {
|
||||
assert!(corner(deg).distance(anchor) > 1.0, "{deg}°: {:?}", corner(deg));
|
||||
}
|
||||
for deg in [0.9, 1.5, 10.0] {
|
||||
assert!(corner(deg).distance(anchor) < 1e-9, "{deg}°: {:?}", corner(deg));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_skips_an_inward_anchor_between_straight_segments() {
|
||||
// A 200 × 100 outline of straight segments with a notch at its top left: (40,40) is the
|
||||
// anchor nearest the box corner, but it turns into the outline, so (60,0) is the corner.
|
||||
let c = |p: (f64, f64)| (p, p, p);
|
||||
let path = outline(&[c((60.0, 0.0)), c((200.0, 0.0)), c((200.0, 100.0)), c((0.0, 100.0)), c((0.0, 60.0)), c((40.0, 40.0))]);
|
||||
let tl = Coons::from_top_object(&path, None).unwrap().corners()[0];
|
||||
assert!(tl.distance(Point::new(60.0, 0.0)) < 1e-9, "{tl:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_corner_tie_goes_to_the_first_anchor() {
|
||||
// Both chamfer anchors lie 30 from the box corner: the first one along the outline, in
|
||||
// the order it was drawn, wins.
|
||||
let c = |p: (f64, f64)| (p, p, p);
|
||||
let tl = |pts: &[Knot]| Coons::from_top_object(&outline(pts), None).unwrap().corners()[0];
|
||||
let from_left = tl(&[c((0.0, 30.0)), c((30.0, 0.0)), c((100.0, 0.0)), c((100.0, 100.0)), c((0.0, 100.0))]);
|
||||
assert!(from_left.distance(Point::new(0.0, 30.0)) < 1e-9, "{from_left:?}");
|
||||
let from_top = tl(&[c((30.0, 0.0)), c((100.0, 0.0)), c((100.0, 100.0)), c((0.0, 100.0)), c((0.0, 30.0))]);
|
||||
assert!(from_top.distance(Point::new(30.0, 0.0)) < 1e-9, "{from_top:?}");
|
||||
// Drawn counter-clockwise, the anchor met first in that order wins.
|
||||
let back = tl(&[c((0.0, 100.0)), c((100.0, 100.0)), c((100.0, 0.0)), c((30.0, 0.0)), c((0.0, 30.0))]);
|
||||
assert!(back.distance(Point::new(30.0, 0.0)) < 1e-9, "{back:?}");
|
||||
let back = tl(&[c((0.0, 30.0)), c((0.0, 100.0)), c((100.0, 100.0)), c((100.0, 0.0)), c((30.0, 0.0))]);
|
||||
assert!(back.distance(Point::new(0.0, 30.0)) < 1e-9, "{back:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reflected_top_object_keeps_the_corners_a_file_gives() {
|
||||
// Reflecting the outline across x = 0 keeps its anchors in the same order, now running
|
||||
// counter-clockwise: the corners stay on the same anchors, so the content is reflected too.
|
||||
let mut path = top_split_at_30();
|
||||
path.transform(Affine::FLIP_X);
|
||||
let c = Coons::from_top_object(&path, Some([1, 2, 3, 4])).unwrap();
|
||||
let want = [(-30.0, 0.0), (-100.0, 0.0), (-100.0, 50.0), (0.0, 50.0)].map(Point::from);
|
||||
assert!(c.corners().iter().zip(want).all(|(p, q)| p.distance(q) < 1e-9), "{:?}", c.corners());
|
||||
let p = c.eval(0.5, 0.5);
|
||||
assert!(p.distance(Point::new(-50.0, 17.5)) < 1e-9, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_keeps_the_corners_a_file_gives() {
|
||||
let same = |a: [Point; 4], b: [Point; 4]| a.iter().zip(b).all(|(p, q)| p.distance(q) < 1e-9);
|
||||
let want = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(Point::from);
|
||||
let c = Coons::from_top_object(&top_split_at_30(), Some([1, 2, 3, 4])).unwrap();
|
||||
assert!(same(c.corners(), want), "{:?}", c.corners());
|
||||
// Drawn the other way round, with the corners counted along that order.
|
||||
let mut back = top_split_at_30();
|
||||
back.subpaths[0].reverse();
|
||||
let c = Coons::from_top_object(&back, Some([3, 2, 1, 0])).unwrap();
|
||||
assert!(same(c.corners(), want), "{:?}", c.corners());
|
||||
// Corners that repeat, run out of order or go past the outline are found from it instead.
|
||||
let found = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(Point::from);
|
||||
for bad in [[0, 0, 3, 4], [2, 1, 3, 4], [1, 2, 3, 9]] {
|
||||
let c = Coons::from_top_object(&top_split_at_30(), Some(bad)).unwrap();
|
||||
assert!(same(c.corners(), found), "{bad:?}: {:?}", c.corners());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_moves_the_top_object_share_to_its_new_anchor() {
|
||||
// Splitting the top curve at t = 0.3 keeps its shape but changes the polygon shares: the
|
||||
// new anchor lands at the first piece's share, not at u = 0.3.
|
||||
let top = CubicBez::new((0.0, 0.0), (40.0, -40.0), (160.0, -40.0), (200.0, 0.0));
|
||||
let (a, b) = (top.subsegment(0.0..0.3), top.subsegment(0.3..1.0));
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), a.p1.into()),
|
||||
(a.p3.into(), a.p2.into(), b.p1.into()),
|
||||
((200.0, 0.0), b.p2.into(), (200.0, 0.0)),
|
||||
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
|
||||
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
|
||||
]);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
let share = polygon(a) / (polygon(a) + polygon(b));
|
||||
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
assert!((share - 0.3).abs() > 0.01, "{share}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangle_top_object_is_the_identity() {
|
||||
let r = Rect::new(10.0, 20.0, 110.0, 70.0);
|
||||
let c = Coons::from_top_object(&shapes::rectangle(r), None).unwrap();
|
||||
for (u, v) in [(0.125, 0.3), (0.9, 0.05), (0.37, 0.81)] {
|
||||
let p = c.eval(u, v);
|
||||
assert!(p.distance(Point::new(10.0 + 100.0 * u, 20.0 + 50.0 * v)) < 1e-9, "({u}, {v}) → {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_straight_line_top_object_maps_onto_its_bounding_box() {
|
||||
let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 40.0))], false));
|
||||
let p = Coons::from_top_object(&line, None).unwrap().eval(0.25, 0.75);
|
||||
assert!(p.distance(Point::new(25.0, 30.0)) < 1e-9, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_spreads_a_segment_by_its_parameter() {
|
||||
// The top side is one straight segment whose handles sit at 60 and 80: its parameter
|
||||
// reaches the middle at x = 63.75, not at 45.
|
||||
let mut top = vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(90.0, 0.0))];
|
||||
top[0].h_out = Point::new(60.0, 0.0);
|
||||
top[1].h_in = Point::new(80.0, 0.0);
|
||||
top.extend([Anchor::corner(Point::new(90.0, 40.0)), Anchor::corner(Point::new(0.0, 40.0))]);
|
||||
let kind = EnvelopeKind::TopObject { path: PathData::single(SubPath::new(top, true)), corners: None };
|
||||
let map = envelope_mapper(&kind, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let p = map(Point::new(5.0, 0.0));
|
||||
assert!(p.distance(Point::new(63.75, 0.0)) < 1e-6, "{p:?}");
|
||||
let p = map(Point::new(5.0, 10.0));
|
||||
assert!(p.distance(Point::new(45.0, 40.0)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_follows_a_curved_side_by_its_parameter() {
|
||||
// The top side bends down from (0,0) to (100,0) through handles at (20,30) and (90,30):
|
||||
// halfway along its parameter it passes (53.75, 22.5).
|
||||
let mut top = vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0))];
|
||||
top[0].h_out = Point::new(20.0, 30.0);
|
||||
top[1].h_in = Point::new(90.0, 30.0);
|
||||
top.extend([Anchor::corner(Point::new(100.0, 80.0)), Anchor::corner(Point::new(0.0, 80.0))]);
|
||||
let path = PathData::single(SubPath::new(top, true));
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
for (u, t) in [(0.5, 0.5), (0.25, 0.25), (0.8125, 0.8125)] {
|
||||
let want = CubicBez::new((0.0, 0.0), (20.0, 30.0), (90.0, 30.0), (100.0, 0.0)).eval(t);
|
||||
let p = c.eval(u, 0.0);
|
||||
assert!(p.distance(want) < 1e-6, "u {u}: {p:?} vs {want:?}");
|
||||
}
|
||||
// Drawn the other way round, the outline gives the same patch.
|
||||
let mut back = path.clone();
|
||||
back.subpaths[0].reverse();
|
||||
let p = Coons::from_top_object(&back, None).unwrap().eval(0.5, 0.0);
|
||||
assert!(p.distance(Point::new(53.75, 22.5)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_of_many_segments_keeps_each_corner() {
|
||||
// The top side zigzags through `n` straight segments, between y = 0 and y = 2.
|
||||
for n in [3, 100] {
|
||||
let w = f64::from(n);
|
||||
let zig = |i: i32| Point::new(f64::from(i) * 100.0 / w, if i % 2 == 1 { 2.0 } else { 0.0 });
|
||||
let mut pts: Vec<Anchor> = (0..=n).map(|i| Anchor::corner(zig(i))).collect();
|
||||
pts.extend([Anchor::corner(Point::new(100.0, 50.0)), Anchor::corner(Point::new(0.0, 50.0))]);
|
||||
let c = Coons::from_top_object(&PathData::single(SubPath::new(pts, true)), None).unwrap();
|
||||
for i in (1..n).filter(|i| n < 10 || [1, 37, 38, 99].contains(i)) {
|
||||
let p = c.eval(f64::from(i) / w, 0.0);
|
||||
assert!(p.distance(zig(i)) < 1e-9, "{n} segments, anchor {i}: {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_mesh_outline_keeps_its_sides_measured_by_length() {
|
||||
let c = Coons::from_path(&top_split_at_30()).unwrap();
|
||||
let p = c.eval(0.5, 0.0);
|
||||
assert!(p.distance(Point::new(50.0, 0.0)) < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_identity() {
|
||||
let r = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
|
||||
+404
-20
@@ -1,6 +1,7 @@
|
||||
use super::expand::{Hooks, Outliner, Warper, map_node};
|
||||
use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, nodes_bounds, surface_of};
|
||||
use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, surface_of};
|
||||
use super::{Affine, Arc, Color, Deserialize, Node, NodeId, NodeKind, PathData, Point, Rect, Serialize, Vec2, yes};
|
||||
use vectorcraft_geom::Homography;
|
||||
|
||||
/// How an envelope distorts its content.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -31,7 +32,14 @@ pub enum EnvelopeKind {
|
||||
handles: Vec<[Vec2; 4]>,
|
||||
},
|
||||
/// The content's bounding box maps onto the outline of this path.
|
||||
TopObject { path: PathData },
|
||||
TopObject {
|
||||
path: PathData,
|
||||
/// The anchors (indices into the outline, the path's largest subpath, in its own order)
|
||||
/// at the top left, top right, bottom right and bottom left corners, as a saved file gives
|
||||
/// them. `None`: the corners are found from the outline.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
corners: Option<[u32; 4]>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Envelope Options → Preserve Shape Using: how a distorted raster keeps the envelope's shape.
|
||||
@@ -127,19 +135,293 @@ impl EnvelopeOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of `content` in the axes of `frame`, with its strokes and geometric. Strokes scale
|
||||
/// with the frame as [`Node::transform`] scales them.
|
||||
/// The bounds of `content` in the axes of `frame`, with its strokes and geometric, type measured by
|
||||
/// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as
|
||||
/// [`Node::transform`] scales them.
|
||||
pub fn envelope_content_boxes(content: &[Arc<Node>], frame: Affine) -> Option<(Rect, Rect)> {
|
||||
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
|
||||
let to_frame = frame.inverse();
|
||||
let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| {
|
||||
let mut m = (**c).clone();
|
||||
m.transform(to_frame, true);
|
||||
(vectorcraft_geom::union_opt(stroked, m.visual_bounds()), vectorcraft_geom::union_opt(plain, m.geometric_bounds()))
|
||||
(vectorcraft_geom::union_opt(stroked, content_box(c, true, to_frame)), vectorcraft_geom::union_opt(plain, content_box(c, false, to_frame)))
|
||||
});
|
||||
Some((stroked?, plain?))
|
||||
}
|
||||
|
||||
/// The geometric bounds an envelope around `content` on the page axes maps from: type, alone or
|
||||
/// in groups and layers, is measured by its glyph outlines, underlines and strikethroughs instead
|
||||
/// of its laid-out box. Type keeps its laid-out box while nothing is registered with
|
||||
/// [`set_type_ink`], and when it draws nothing.
|
||||
pub fn envelope_content_bounds(content: &[Arc<Node>]) -> Option<Rect> {
|
||||
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY)))
|
||||
}
|
||||
|
||||
/// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by
|
||||
/// the given transform (outlines mapped point by point) and, for type in perspective, then drawn
|
||||
/// through its projection and mapped by the second transform. `None` when it draws nothing. Type is
|
||||
/// laid out above this crate, so the text crate registers one with [`set_type_ink`].
|
||||
pub type TypeInk = fn(&crate::TextObject, Affine, Option<(Homography, Affine)>) -> Option<Rect>;
|
||||
|
||||
/// What [`TypeInk`] maps type's text space by: a transform, and a projection with the transform
|
||||
/// after it.
|
||||
type TypeMap = (Affine, Option<(Homography, Affine)>);
|
||||
|
||||
static TYPE_INK: std::sync::OnceLock<(TypeInk, crate::hit::LiveInputs)> = std::sync::OnceLock::new();
|
||||
|
||||
/// Register how envelopes measure type, and a number that changes whenever what it reads besides
|
||||
/// the type changes, such as the installed fonts (the first registration stays).
|
||||
pub fn set_type_ink(f: TypeInk, inputs: crate::hit::LiveInputs) {
|
||||
// Already set: the same measure, registered by another session, an import or a renderer.
|
||||
let _ = TYPE_INK.set((f, inputs));
|
||||
}
|
||||
|
||||
/// How many entries each table of [`TypeInks`] holds before it is emptied.
|
||||
const TYPE_INK_KEPT: usize = 1024;
|
||||
|
||||
/// `map`, bit for bit, for a table key.
|
||||
fn map_bits(map: &TypeMap) -> [u64; 21] {
|
||||
let mut bits = [0; 21];
|
||||
let (m, projection) = map;
|
||||
for (b, v) in bits.iter_mut().zip(m.as_coeffs()) {
|
||||
*b = v.to_bits();
|
||||
}
|
||||
if let Some((h, after)) = projection {
|
||||
for (b, v) in bits[6..].iter_mut().zip(h.to_array().into_iter().chain(after.as_coeffs())) {
|
||||
*b = v.to_bits();
|
||||
}
|
||||
}
|
||||
bits
|
||||
}
|
||||
|
||||
/// A key of [`TypeInks::nodes`]: the object's address, the map its outlines are measured in (an
|
||||
/// affine map without its move) and the inputs number registered with [`set_type_ink`].
|
||||
type NodeKey = (usize, [u64; 21], u64);
|
||||
|
||||
/// A key of [`TypeInks::content`]: two 64-bit hashes of the type without its transform's move and
|
||||
/// its layout caches ([`content_hash`]), the map its outlines are measured in, and the inputs number.
|
||||
type ContentKey = ([u64; 2], [u64; 21], u64);
|
||||
|
||||
/// Type measured by [`type_ink`] on one thread, by the map it is measured in and the inputs
|
||||
/// number: by the object (an unchanged object is found without being read),
|
||||
/// and by its content (a moved or copied object is found without laying it out again). Neither
|
||||
/// table keeps a copy of the type.
|
||||
#[derive(Default)]
|
||||
struct TypeInks {
|
||||
/// By the object's address, with a weak pointer that keeps the address from being reused.
|
||||
nodes: std::collections::HashMap<NodeKey, (std::sync::Weak<Node>, Option<Rect>)>,
|
||||
/// By the type's content.
|
||||
content: std::collections::HashMap<ContentKey, Option<Rect>>,
|
||||
}
|
||||
|
||||
/// Where [`TypeInks::find`] did not find type: its keys in both tables (no content key for type
|
||||
/// that could not be hashed whole).
|
||||
struct Missing {
|
||||
by_node: NodeKey,
|
||||
content: Option<ContentKey>,
|
||||
}
|
||||
|
||||
impl TypeInks {
|
||||
/// The kept box of type node `n` (holding `t`) mapped by `map`, or the keys to keep it under
|
||||
/// once it is measured.
|
||||
fn find(&mut self, n: &Arc<Node>, t: &crate::TextObject, map: &TypeMap, inputs: u64) -> Result<Option<Rect>, Box<Missing>> {
|
||||
// While the table holds a weak pointer to `n`'s allocation, no other object can be at that
|
||||
// address, and `n` can't be changed in place (`Arc::get_mut` refuses it and `Arc::make_mut`
|
||||
// moves it).
|
||||
let by_node = (Arc::as_ptr(n) as usize, map_bits(map), inputs);
|
||||
if let Some((_, ink)) = self.nodes.get(&by_node) {
|
||||
return Ok(*ink);
|
||||
}
|
||||
// Shrink Text to Fit lays type out by its size on the page, so only a move keeps its layout.
|
||||
let [a, b, c, d, _, _] = t.xf.as_coeffs();
|
||||
let mut text = t.clone();
|
||||
text.xf = Affine::new([a, b, c, d, 0.0, 0.0]);
|
||||
text.cached_bounds = None;
|
||||
text.cached_baselines.clear();
|
||||
let content = content_hash(&text).map(|hash| (hash, by_node.1, inputs));
|
||||
match content.and_then(|key| self.content.get(&key)) {
|
||||
Some(ink) => {
|
||||
let ink = *ink;
|
||||
self.keep_node(n, by_node, ink);
|
||||
Ok(ink)
|
||||
}
|
||||
None => Err(Box::new(Missing { by_node, content })),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the box `ink` measured for type node `n` under the keys `missing`.
|
||||
fn keep(&mut self, n: &Arc<Node>, missing: Missing, ink: Option<Rect>) {
|
||||
if let Some(key) = missing.content {
|
||||
if self.content.len() >= TYPE_INK_KEPT {
|
||||
self.content.clear();
|
||||
}
|
||||
self.content.insert(key, ink);
|
||||
}
|
||||
self.keep_node(n, missing.by_node, ink);
|
||||
}
|
||||
|
||||
fn keep_node(&mut self, n: &Arc<Node>, by_node: NodeKey, ink: Option<Rect>) {
|
||||
if self.nodes.len() >= TYPE_INK_KEPT {
|
||||
self.nodes.retain(|_, (weak, _)| weak.strong_count() > 0);
|
||||
if self.nodes.len() >= TYPE_INK_KEPT {
|
||||
self.nodes.clear();
|
||||
}
|
||||
}
|
||||
self.nodes.insert(by_node, (Arc::downgrade(n), ink));
|
||||
}
|
||||
}
|
||||
|
||||
/// Two independent 64-bit hashes of `text` as saved (the layout caches are not saved), with what
|
||||
/// layout reads that is not saved: whether its first paragraph continues a thread and the bounds
|
||||
/// of its inline graphics. `None` when it can't be written whole.
|
||||
fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> {
|
||||
use std::hash::Hasher;
|
||||
/// Feeds what is written to two hashers.
|
||||
struct Feed([std::collections::hash_map::DefaultHasher; 2]);
|
||||
impl std::io::Write for Feed {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
for h in &mut self.0 {
|
||||
h.write(buf);
|
||||
}
|
||||
Ok(buf.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let mut feed = Feed(Default::default());
|
||||
// The second hasher starts from another state.
|
||||
feed.0[1].write_u8(1);
|
||||
serde_json::to_writer(&mut feed, text).ok()?;
|
||||
let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits)));
|
||||
for h in &mut feed.0 {
|
||||
h.write_u8(u8::from(text.first_para_continues));
|
||||
for b in inline_bounds.clone() {
|
||||
match b {
|
||||
None => h.write_u8(0),
|
||||
Some(bits) => {
|
||||
h.write_u8(1);
|
||||
bits.into_iter().for_each(|v| h.write_u64(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let [a, b] = feed.0;
|
||||
Some([a.finish(), b.finish()])
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// The type [`type_ink`] measured on this thread.
|
||||
static TYPE_INKS: std::cell::RefCell<TypeInks> = std::cell::RefCell::new(TypeInks::default());
|
||||
}
|
||||
|
||||
/// The box of the glyph outlines of type node `n` (holding `t`) with its text space mapped by `m`
|
||||
/// ([`set_type_ink`]) and, for type in perspective, drawn through `projection` and mapped by its
|
||||
/// second transform; measured again when `t`, the maps (without a move of `m` when there is no
|
||||
/// projection) or the registered inputs number change. `None` while nothing is registered.
|
||||
fn type_ink(n: &Arc<Node>, t: &crate::TextObject, m: Affine, projection: Option<(Homography, Affine)>) -> Option<Option<Rect>> {
|
||||
let (f, inputs) = TYPE_INK.get()?;
|
||||
let inputs = inputs();
|
||||
// Without a projection the type is measured without the move, which is added to the box.
|
||||
let [a, b, c, d, e, g] = m.as_coeffs();
|
||||
let (map, offset) = match projection {
|
||||
None => ((Affine::new([a, b, c, d, 0.0, 0.0]), None), Vec2::new(e, g)),
|
||||
Some(p) => ((m, Some(p)), Vec2::ZERO),
|
||||
};
|
||||
let ink = match TYPE_INKS.with_borrow_mut(|kept| kept.find(n, t, &map, inputs)) {
|
||||
Ok(ink) => ink,
|
||||
Err(missing) => {
|
||||
// Measured outside the borrow: laying type out may measure other type.
|
||||
let ink = f(t, map.0, map.1);
|
||||
TYPE_INKS.with_borrow_mut(|kept| kept.keep(n, *missing, ink));
|
||||
ink
|
||||
}
|
||||
};
|
||||
Some(ink.map(|r| r + offset))
|
||||
}
|
||||
|
||||
/// Add to `typed` the address of `n` and of each group and layer in it that holds type, which
|
||||
/// [`content_box`] measures by its glyphs; is there type in `n`? One walk of the tree.
|
||||
fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
|
||||
let holds = match &n.kind {
|
||||
NodeKind::Text(_) => true,
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().fold(false, |holds, c| find_type(c, typed) | holds),
|
||||
_ => false,
|
||||
};
|
||||
if holds {
|
||||
typed.insert(n as *const Node as usize);
|
||||
}
|
||||
holds
|
||||
}
|
||||
|
||||
/// The box of `n` an envelope maps from, in the axes `to` takes the page to: its geometric bounds,
|
||||
/// or with `stroked` its visual bounds (strokes scaled by `to` as [`Node::transform`] scales them),
|
||||
/// with type measured by its glyph outlines ([`type_ink`]) instead of its laid-out box, in groups
|
||||
/// and layers too. Type is laid out as it is on the page, and its outlines are then taken into
|
||||
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box.
|
||||
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine) -> Option<Rect> {
|
||||
let mut typed = std::collections::HashSet::new();
|
||||
find_type(n, &mut typed);
|
||||
content_box_in(n, stroked, to, &typed)
|
||||
}
|
||||
|
||||
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
|
||||
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>) -> Option<Rect> {
|
||||
// `n` in the axes of `to`.
|
||||
let moved = || {
|
||||
if to == Affine::IDENTITY {
|
||||
return std::borrow::Cow::Borrowed(&**n);
|
||||
}
|
||||
let mut m = (**n).clone();
|
||||
m.transform(to, true);
|
||||
std::borrow::Cow::Owned(m)
|
||||
};
|
||||
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
|
||||
if !typed.contains(&(Arc::as_ptr(n) as usize)) {
|
||||
return own(&moved());
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
// Type in perspective: its outlines as its projection draws them.
|
||||
let ink = match n.projection() {
|
||||
None => type_ink(n, t, to * t.xf, None),
|
||||
Some(h) => type_ink(n, t, t.xf, Some((h, to))),
|
||||
}
|
||||
.flatten();
|
||||
let m = moved();
|
||||
let Some(ink) = ink else { return own(&m) };
|
||||
if !stroked {
|
||||
return Some(ink);
|
||||
}
|
||||
let (Some(v), Some(g)) = (m.visual_bounds(), m.geometric_bounds()) else { return Some(ink) };
|
||||
Some(Rect::new(
|
||||
ink.x0 - (g.x0 - v.x0).max(0.0),
|
||||
ink.y0 - (g.y0 - v.y0).max(0.0),
|
||||
ink.x1 + (v.x1 - g.x1).max(0.0),
|
||||
ink.y1 + (v.y1 - g.y1).max(0.0),
|
||||
))
|
||||
}
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
// A clipping path that paints strokes over the clip edge, as in `Node::visual_bounds`.
|
||||
let clip = children.first()?;
|
||||
content_box_in(clip, stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), to, typed)
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
let members = n.editing_children().iter();
|
||||
if stroked {
|
||||
// The container's own strokes, scaled by `to` as `Node::transform` scales them,
|
||||
// without copying its members.
|
||||
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
|
||||
own_strokes.appearance = n.appearance.clone();
|
||||
own_strokes.transform(to, true);
|
||||
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed)))
|
||||
} else {
|
||||
members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed)))
|
||||
}
|
||||
}
|
||||
_ => own(&moved()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
|
||||
/// content with no width or no height, or for margins an `f32` can't hold.
|
||||
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
|
||||
@@ -243,7 +525,7 @@ pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option<GradientMesh>)> {
|
||||
Some((grid.lines(), Some(grid)))
|
||||
}
|
||||
EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
|
||||
EnvelopeKind::TopObject { path } => Some((path.clone(), None)),
|
||||
EnvelopeKind::TopObject { path, .. } => Some((path.clone(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,20 +547,13 @@ pub struct EnvelopeMap<'a> {
|
||||
}
|
||||
|
||||
impl<'a> EnvelopeMap<'a> {
|
||||
/// The map of an envelope of `kind` around `content` with `frame` and `options`. `None` when
|
||||
/// the content has no bounds.
|
||||
/// The map of an envelope of `kind` around `content` with `frame` and `options`, from the
|
||||
/// content's bounds with type measured by its glyph outlines ([`envelope_content_bounds`]).
|
||||
/// `None` when the content has no bounds.
|
||||
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Self> {
|
||||
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
|
||||
let to_frame = frame.inverse();
|
||||
let src = if frame == Affine::IDENTITY {
|
||||
nodes_bounds(content)?
|
||||
} else {
|
||||
content.iter().try_fold(None, |acc, c| {
|
||||
let mut m = (**c).clone();
|
||||
m.transform(to_frame, false);
|
||||
Some(vectorcraft_geom::union_opt(acc, m.geometric_bounds()))
|
||||
})??
|
||||
};
|
||||
let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?;
|
||||
let src = options.source_box(src);
|
||||
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
|
||||
}
|
||||
@@ -374,7 +649,116 @@ pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine
|
||||
let first = *points.first()?;
|
||||
Some(points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => path.bounds(),
|
||||
EnvelopeKind::TopObject { path, .. } => path.bounds(),
|
||||
EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame, options)?.bounds(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{CharStyle, TextObject};
|
||||
|
||||
/// Look `n` up in `kept`, measuring it (and counting the measures) when it isn't there.
|
||||
fn look_up(kept: &mut TypeInks, n: &Arc<Node>, linear: Affine, measured: &mut usize) -> Option<Rect> {
|
||||
let NodeKind::Text(t) = &n.kind else { panic!("type") };
|
||||
match kept.find(n, t, &(linear, None), 0) {
|
||||
Ok(ink) => ink,
|
||||
Err(missing) => {
|
||||
*measured += 1;
|
||||
let ink = Some(Rect::new(0.0, 0.0, *measured as f64, 1.0));
|
||||
kept.keep(n, *missing, ink);
|
||||
ink
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn type_node(i: usize, text: &str) -> Arc<Node> {
|
||||
let t = TextObject::point(Point::new(i as f64 * 10.0, 0.0), text, CharStyle::default());
|
||||
Arc::new(Node::new(NodeId(i as u64), NodeKind::Text(Box::new(t))))
|
||||
}
|
||||
|
||||
/// Many type objects are each measured once however often they are looked up; a moved or copied
|
||||
/// object is found by its content, and a changed one or another transform is measured again.
|
||||
#[test]
|
||||
fn measured_type_is_kept_for_many_objects() {
|
||||
let mut kept = TypeInks::default();
|
||||
let mut measured = 0;
|
||||
let nodes: Vec<_> = (0..200).map(|i| type_node(i, &format!("Type {i}"))).collect();
|
||||
for _ in 0..5 {
|
||||
for n in &nodes {
|
||||
look_up(&mut kept, n, Affine::IDENTITY, &mut measured);
|
||||
}
|
||||
}
|
||||
assert_eq!(measured, 200);
|
||||
let mut moved = (*nodes[7]).clone();
|
||||
moved.transform(Affine::translate((300.0, 40.0)), true);
|
||||
let moved = Arc::new(moved);
|
||||
assert_eq!(look_up(&mut kept, &moved, Affine::IDENTITY, &mut measured), look_up(&mut kept, &nodes[7], Affine::IDENTITY, &mut measured));
|
||||
assert_eq!(measured, 200, "a moved object is found by its content");
|
||||
let changed = type_node(7, "Changed");
|
||||
look_up(&mut kept, &changed, Affine::IDENTITY, &mut measured);
|
||||
assert_eq!(measured, 201, "a changed object is measured again");
|
||||
look_up(&mut kept, &nodes[7], Affine::rotate(0.5), &mut measured);
|
||||
assert_eq!(measured, 202, "another transform is measured again");
|
||||
}
|
||||
|
||||
/// Type that differs only in what layout reads but files don't save (a first paragraph that
|
||||
/// continues a thread, the resolved bounds of an inline graphic) is measured again.
|
||||
#[test]
|
||||
fn type_that_differs_in_what_is_not_saved_is_measured_again() {
|
||||
let mut kept = TypeInks::default();
|
||||
let mut measured = 0;
|
||||
let mut t = TextObject::point(Point::ZERO, "Type", CharStyle::default());
|
||||
t.runs.push(crate::TextRun::new("", CharStyle::default()));
|
||||
t.runs[1].inline = Some(crate::InlineArt { symbol: "S".into(), scale: 1.0, baseline_shift: 0.0, bounds: None });
|
||||
let node = |t: &TextObject| Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
|
||||
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
|
||||
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
|
||||
assert_eq!(measured, 1, "a copy is found by its content");
|
||||
t.first_para_continues = true;
|
||||
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
|
||||
assert_eq!(measured, 2, "a first paragraph that continues a thread");
|
||||
if let Some(inline) = &mut t.runs[1].inline {
|
||||
inline.bounds = Some(Rect::new(0.0, 0.0, 10.0, 20.0));
|
||||
}
|
||||
look_up(&mut kept, &node(&t), Affine::IDENTITY, &mut measured);
|
||||
assert_eq!(measured, 3, "an inline graphic's bounds");
|
||||
}
|
||||
|
||||
/// A stroked group of type in a scaled frame reaches past its members by its own strokes scaled
|
||||
/// with the frame, as the group moved into the frame does; deeply nested groups are measured in
|
||||
/// one walk each.
|
||||
#[test]
|
||||
fn a_stroked_group_of_type_is_measured_with_its_strokes_in_the_frame() {
|
||||
let text = type_node(1, "Group");
|
||||
let mut group = Node::group(NodeId(2), vec![text.clone()]);
|
||||
group.appearance = crate::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 4.0).into();
|
||||
let group = Arc::new(group);
|
||||
let to = Affine::scale(2.0);
|
||||
let mut moved = (*group).clone();
|
||||
moved.transform(to, true);
|
||||
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to)));
|
||||
assert!(want.is_some());
|
||||
assert_eq!(content_box(&group, true, to), want);
|
||||
let mut nested = group;
|
||||
for i in 0..300 {
|
||||
nested = Arc::new(Node::group(NodeId(10 + i), vec![nested]));
|
||||
}
|
||||
assert!(content_box(&nested, false, Affine::IDENTITY).is_some());
|
||||
}
|
||||
|
||||
/// A table that fills up is emptied instead of growing, and what is looked up after that is
|
||||
/// measured again.
|
||||
#[test]
|
||||
fn the_tables_stay_bounded() {
|
||||
let mut kept = TypeInks::default();
|
||||
let mut measured = 0;
|
||||
let nodes: Vec<_> = (0..TYPE_INK_KEPT + 10).map(|i| type_node(i, &format!("Type {i}"))).collect();
|
||||
for n in &nodes {
|
||||
look_up(&mut kept, n, Affine::IDENTITY, &mut measured);
|
||||
}
|
||||
assert!(kept.content.len() <= TYPE_INK_KEPT && kept.nodes.len() <= TYPE_INK_KEPT, "{} {}", kept.content.len(), kept.nodes.len());
|
||||
assert_eq!(measured, TYPE_INK_KEPT + 10);
|
||||
}
|
||||
}
|
||||
+262
-7
@@ -73,13 +73,16 @@ const SIDE: usize = 65;
|
||||
|
||||
/// Four boundary curves (top TL→TR, right TR→BR, bottom BL→BR, left TL→BL), each resampled to
|
||||
/// [`SIDE`] points, from the outline of a closed path split at the points nearest its bounding
|
||||
/// box corners.
|
||||
/// box corners. [`Coons::from_top_object`] samples its sides at the places `knots` gives instead.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Coons {
|
||||
top: Vec<Point>,
|
||||
right: Vec<Point>,
|
||||
bottom: Vec<Point>,
|
||||
left: Vec<Point>,
|
||||
/// Where along its side (0 to 1, rising) each point of the top, right, bottom and left side
|
||||
/// lies; `None` when the points are evenly spaced.
|
||||
knots: Option<Box<[Vec<f64>; 4]>>,
|
||||
}
|
||||
|
||||
impl Coons {
|
||||
@@ -87,9 +90,11 @@ impl Coons {
|
||||
pub fn rect(r: Rect) -> Self {
|
||||
let line = |a: Point, b: Point| (0..SIDE).map(|i| a.lerp(b, i as f64 / (SIDE - 1) as f64)).collect::<Vec<_>>();
|
||||
let (tl, tr, br, bl) = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1));
|
||||
Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl) }
|
||||
Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl), knots: None }
|
||||
}
|
||||
|
||||
/// The patch of `path`'s outline, each side measured by its length: equal steps in `u` or `v`
|
||||
/// cover equal lengths of the side.
|
||||
pub fn from_path(path: &PathData) -> Option<Self> {
|
||||
// The largest subpath is the outline.
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
@@ -136,7 +141,145 @@ impl Coons {
|
||||
bottom.reverse();
|
||||
let mut left = resample(&arc(bl, tl), SIDE);
|
||||
left.reverse();
|
||||
Some(Self { top, right, bottom, left })
|
||||
Some(Self { top, right, bottom, left, knots: None })
|
||||
}
|
||||
|
||||
/// The patch of a top object's outline (the largest subpath of `path`), split into four sides
|
||||
/// at its corners. Each piece of a side between two anchors or corners takes a share of `u` or
|
||||
/// `v` in proportion to the length of its control polygon, spread along the piece by its own
|
||||
/// curve parameter. A segment without handles counts as a cubic with its handles a third of
|
||||
/// the way along, so the content spreads evenly along it. `corners` are the anchors (indices
|
||||
/// into the outline, in its own order) at the top left, top right, bottom right and bottom
|
||||
/// left, as a saved file gives them. They stay on those anchors when they run the way the
|
||||
/// outline does or the opposite way, so a reflected outline keeps them; without them, or when
|
||||
/// they don't fit the outline, each corner is found from the outline ([`top_object_corner`]).
|
||||
/// A straight segment closes an open subpath, and segments of no length are left out. A top
|
||||
/// object's envelope maps onto this patch.
|
||||
pub fn from_top_object(path: &PathData, corners: Option<[u32; 4]>) -> Option<Self> {
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
let mut sp = sp.clone();
|
||||
let count = sp.anchors.len();
|
||||
// Stored corners count only when they are distinct anchors met in order around the outline.
|
||||
let fits = |c: &[usize; 4]| {
|
||||
if !c.iter().all(|i| *i < count) {
|
||||
return false;
|
||||
}
|
||||
let gaps: Vec<usize> = (0..4).map(|k| (c[(k + 1) % 4] + count - c[k]) % count).collect();
|
||||
gaps.iter().all(|g| *g > 0) && gaps.iter().sum::<usize>() == count
|
||||
};
|
||||
let given = corners.map(|c| c.map(|i| i as usize));
|
||||
// Stored corners met in the outline's own order keep it as drawn, even counter-clockwise
|
||||
// (a reflected outline). Otherwise orient it clockwise in y-down (TL → TR → BR → BL).
|
||||
let mut corners = given.filter(fits);
|
||||
let reversed = corners.is_none() && sp.signed_area() < 0.0;
|
||||
if reversed {
|
||||
sp.reverse();
|
||||
corners = given.map(|c| c.map(|i| count.saturating_sub(1).saturating_sub(i))).filter(fits);
|
||||
}
|
||||
// Each segment, and whether it is straight: a straight one's parameter runs evenly along it.
|
||||
let line = |a: Point, b: Point| (CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b), true);
|
||||
let mut segs: Vec<(usize, (CubicBez, bool))> = (0..sp.segment_count())
|
||||
.map(|i| {
|
||||
let c = sp.segment(i);
|
||||
(i, if sp.segment_is_line(i) { line(c.p0, c.p3) } else { (c, false) })
|
||||
})
|
||||
.collect();
|
||||
if !sp.closed
|
||||
&& let (Some(a), Some(b)) = (sp.anchors.last(), sp.anchors.first())
|
||||
{
|
||||
segs.push((count.saturating_sub(1), line(a.p, b.p)));
|
||||
}
|
||||
segs.retain(|(_, (c, _))| [c.p1, c.p2, c.p3].iter().any(|p| p.distance(c.p0) > 1e-9));
|
||||
// The kept segment that anchor `k` starts (a segment of no length starts where the next begins).
|
||||
let starts: Vec<usize> = segs.iter().map(|(i, _)| *i).collect();
|
||||
// Where each kept segment and the anchor it starts at come in the outline as drawn: a tie
|
||||
// between corners goes to the one met first there.
|
||||
let order: Vec<(usize, usize)> = starts
|
||||
.iter()
|
||||
.map(|&i| if reversed { (count.saturating_sub(1).saturating_sub(i), (2 * count).saturating_sub(2 + i) % count.max(1)) } else { (i, i) })
|
||||
.collect();
|
||||
let segs: Vec<(CubicBez, bool)> = segs.into_iter().map(|(_, s)| s).collect();
|
||||
let r = segs.iter().map(|(c, _)| c.bounding_box()).reduce(|a, b| a.union(b)).or_else(|| path.bounds())?;
|
||||
// An outline of fewer than three points (a straight line there and back) maps onto its
|
||||
// bounding box, as in `from_path`.
|
||||
if segs.len() < 2 || (segs.len() == 2 && segs.iter().all(|(_, straight)| *straight)) {
|
||||
return Some(Self::rect(r));
|
||||
}
|
||||
let n = segs.len() as f64;
|
||||
let at = |s: f64| {
|
||||
let s = s.rem_euclid(n);
|
||||
let i = (s.floor() as usize).min(segs.len() - 1);
|
||||
segs.get(i).map_or(Point::ZERO, |(c, _)| c.eval((s - i as f64).clamp(0.0, 1.0)))
|
||||
};
|
||||
// The side from `a` to `b`: its points, and where along it (0 to 1) each lies. It runs
|
||||
// through pieces of segments, split at `a` and `b`. Each piece takes its share of the side
|
||||
// by the length of its control polygon and holds points at even steps of its parameter
|
||||
// (at least 16, and at least `SIDE` points on the side), its ends included. A side of
|
||||
// many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` points,
|
||||
// or one for each piece when it has more pieces than that.
|
||||
let side = |a: f64, b: f64| {
|
||||
let span = (b - a).rem_euclid(n);
|
||||
if !(span.is_finite() && span > 0.0) {
|
||||
return (vec![at(a), at(a)], vec![0.0, 1.0]);
|
||||
}
|
||||
let mut pieces: Vec<CubicBez> = vec![];
|
||||
let (mut s, end) = (a, a + span);
|
||||
while s < end - 1e-12 && pieces.len() <= segs.len() {
|
||||
let i = s.floor();
|
||||
let next = (i + 1.0).min(end);
|
||||
if let Some((c, _)) = segs.get((i as usize) % segs.len()) {
|
||||
pieces.push(c.subsegment((s - i).clamp(0.0, 1.0)..(next - i).clamp(0.0, 1.0)));
|
||||
}
|
||||
s = next;
|
||||
}
|
||||
let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3);
|
||||
let mut weights: Vec<f64> = pieces.iter().map(polygon).collect();
|
||||
let mut total: f64 = weights.iter().sum();
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
weights.iter_mut().for_each(|w| *w = 1.0);
|
||||
total = weights.len().max(1) as f64;
|
||||
}
|
||||
let count = pieces.len().max(1);
|
||||
let per = 16usize.max((SIDE - 1).div_ceil(count));
|
||||
let per = if count * per < MAX_SIDE_POINTS { per } else { (MAX_SIDE_POINTS / count).max(1) };
|
||||
let mut pts = vec![pieces.first().map_or_else(|| at(a), |c| c.p0)];
|
||||
let mut knots = vec![0.0];
|
||||
let mut before = 0.0;
|
||||
for (c, w) in pieces.iter().zip(&weights) {
|
||||
for k in 1..=per {
|
||||
let f = k as f64 / per as f64;
|
||||
pts.push(c.eval(f));
|
||||
knots.push((before + w * f) / total);
|
||||
}
|
||||
before += w;
|
||||
}
|
||||
if let Some(last) = knots.last_mut() {
|
||||
*last = 1.0;
|
||||
}
|
||||
(pts, knots)
|
||||
};
|
||||
let (tl, tr, br, bl) = match corners {
|
||||
// Anchor `k` sits at the start of the first kept segment from it on.
|
||||
Some(c) => {
|
||||
let place = |k: usize| starts.iter().position(|i| *i >= k).unwrap_or(0) as f64;
|
||||
(place(c[0]), place(c[1]), place(c[2]), place(c[3]))
|
||||
}
|
||||
None => {
|
||||
let corner = |q: Point| top_object_corner(&segs, &order, r, q);
|
||||
(corner(Point::new(r.x0, r.y0)), corner(Point::new(r.x1, r.y0)), corner(Point::new(r.x1, r.y1)), corner(Point::new(r.x0, r.y1)))
|
||||
}
|
||||
};
|
||||
let flip = |(mut p, mut u): (Vec<Point>, Vec<f64>)| {
|
||||
p.reverse();
|
||||
u.reverse();
|
||||
u.iter_mut().for_each(|x| *x = 1.0 - *x);
|
||||
(p, u)
|
||||
};
|
||||
let (top, top_u) = side(tl, tr);
|
||||
let (right, right_u) = side(tr, br);
|
||||
let (bottom, bottom_u) = flip(side(br, bl));
|
||||
let (left, left_u) = flip(side(bl, tl));
|
||||
Some(Self { top, right, bottom, left, knots: Some(Box::new([top_u, right_u, bottom_u, left_u])) })
|
||||
}
|
||||
|
||||
/// The point at `u` along a side; past its ends the end segments go on straight (art an
|
||||
@@ -147,10 +290,36 @@ impl Coons {
|
||||
side[i].lerp(side[i + 1], s - i as f64)
|
||||
}
|
||||
|
||||
/// The point at `u` along a side whose points lie at `knots` (rising, 0 to 1); past its ends
|
||||
/// the end segments go on straight, as in [`Self::sample`].
|
||||
fn sample_at(side: &[Point], knots: &[f64], u: f64) -> Point {
|
||||
if side.len() < 2 || side.len() != knots.len() {
|
||||
return side.first().copied().unwrap_or_default();
|
||||
}
|
||||
let i = knots.partition_point(|k| *k <= u).clamp(1, side.len() - 1) - 1;
|
||||
let (k0, k1) = (knots[i], knots[i + 1]);
|
||||
let f = if k1 > k0 { (u - k0) / (k1 - k0) } else { 0.0 };
|
||||
side[i].lerp(side[i + 1], f)
|
||||
}
|
||||
|
||||
/// The point at `u` along side `which` (0 top, 1 right, 2 bottom, 3 left).
|
||||
fn side_at(&self, which: usize, u: f64) -> Point {
|
||||
let side = match which {
|
||||
0 => &self.top,
|
||||
1 => &self.right,
|
||||
2 => &self.bottom,
|
||||
_ => &self.left,
|
||||
};
|
||||
match self.knots.as_deref().and_then(|k| k.get(which)) {
|
||||
Some(knots) => Self::sample_at(side, knots, u),
|
||||
None => Self::sample(side, u),
|
||||
}
|
||||
}
|
||||
|
||||
/// The surface point at (u, v) ∈ [0,1]².
|
||||
pub fn eval(&self, u: f64, v: f64) -> Point {
|
||||
let (t, b, l, r) = (Self::sample(&self.top, u), Self::sample(&self.bottom, u), Self::sample(&self.left, v), Self::sample(&self.right, v));
|
||||
let (p00, p10, p01, p11) = (self.top[0], self.top[SIDE - 1], self.bottom[0], self.bottom[SIDE - 1]);
|
||||
let (t, b, l, r) = (self.side_at(0, u), self.side_at(2, u), self.side_at(3, v), self.side_at(1, v));
|
||||
let [p00, p10, p11, p01] = self.corners();
|
||||
let c = (1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * r.to_vec2()
|
||||
- ((1.0 - u) * (1.0 - v) * p00.to_vec2() + u * (1.0 - v) * p10.to_vec2() + (1.0 - u) * v * p01.to_vec2() + u * v * p11.to_vec2());
|
||||
c.to_point()
|
||||
@@ -158,7 +327,93 @@ impl Coons {
|
||||
|
||||
/// The four corners TL, TR, BR, BL.
|
||||
pub fn corners(&self) -> [Point; 4] {
|
||||
[self.top[0], self.top[SIDE - 1], self.bottom[SIDE - 1], self.bottom[0]]
|
||||
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
|
||||
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
|
||||
/// anchors.
|
||||
const MAX_SIDE_POINTS: usize = 1 << 16;
|
||||
|
||||
/// How far into the outline's bounding box, as a share of its width and of its height, a corner
|
||||
/// of a top object looks for an anchor.
|
||||
const CORNER_REACH: f64 = 0.475;
|
||||
|
||||
/// A handle this long (in points) or shorter makes its anchor a corner of a top object.
|
||||
const SHORT_HANDLE: f64 = 0.01;
|
||||
|
||||
/// An anchor whose tangent directions, as unit vectors, differ by less than this in x and in y is
|
||||
/// smooth, and is not a corner of a top object.
|
||||
const SMOOTH_TURN: f64 = 0.01;
|
||||
|
||||
/// A top object's corner this close (in curve parameter) to either end of its segment moves onto
|
||||
/// the anchor there.
|
||||
const CORNER_END_SNAP: f64 = 0.005;
|
||||
|
||||
/// Is the anchor at `a`, reached by handle `h_in` and left by handle `h_out` on an outline that
|
||||
/// runs clockwise on screen, a corner of a top object? A handle of [`SHORT_HANDLE`] or shorter
|
||||
/// makes it one. Otherwise its tangent directions must differ by [`SMOOTH_TURN`] or more and turn
|
||||
/// clockwise, so it points out of the outline. A straight segment's handles here are the ones
|
||||
/// [`Coons::from_top_object`] gives it, a third of the way along, so an anchor between two
|
||||
/// straight segments longer than three times [`SHORT_HANDLE`] is a corner only when it turns out
|
||||
/// of the outline.
|
||||
fn top_object_corner_anchor(h_in: Point, a: Point, h_out: Point) -> bool {
|
||||
let (vin, vout) = (a - h_in, h_out - a);
|
||||
let (len_in, len_out) = (vin.hypot(), vout.hypot());
|
||||
if len_in <= SHORT_HANDLE || len_out <= SHORT_HANDLE {
|
||||
return true;
|
||||
}
|
||||
let (ui, uo) = (vin / len_in, vout / len_out);
|
||||
if (ui.x - uo.x).abs() < SMOOTH_TURN && (ui.y - uo.y).abs() < SMOOTH_TURN {
|
||||
return false;
|
||||
}
|
||||
ui.cross(uo) >= 0.0
|
||||
}
|
||||
|
||||
/// Where along `segs` (segment index + parameter, in [0, n)) the corner of a top object nearest
|
||||
/// corner `q` of its bounding box `r` lies, for an outline that runs clockwise on screen. It is
|
||||
/// the nearest anchor to `q` that is a corner ([`top_object_corner_anchor`]) and lies within
|
||||
/// [`CORNER_REACH`] of the box's width and height from `q`. Without one, it is the nearest point
|
||||
/// of the outline to `q`, moved onto its segment's anchor when within [`CORNER_END_SNAP`] of
|
||||
/// either end. `order` gives where each segment's first anchor and the segment itself come in the
|
||||
/// outline as drawn, which may run the other way; on a tie the one met first there wins.
|
||||
fn top_object_corner(segs: &[(CubicBez, bool)], order: &[(usize, usize)], r: Rect, q: Point) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
let n = segs.len();
|
||||
if n == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
let rank = |i: usize| order.get(i).copied().unwrap_or((i, i));
|
||||
let (reach_x, reach_y) = (r.width() * CORNER_REACH, r.height() * CORNER_REACH);
|
||||
let mut best: Option<(f64, usize, usize)> = None;
|
||||
for i in 0..n {
|
||||
let (Some((prev, _)), Some((cur, _))) = (segs.get((i + n - 1) % n), segs.get(i)) else { continue };
|
||||
let a = cur.p0;
|
||||
if (a.x - q.x).abs() > reach_x || (a.y - q.y).abs() > reach_y || !top_object_corner_anchor(prev.p2, a, cur.p1) {
|
||||
continue;
|
||||
}
|
||||
let (d, k) = (a.distance_squared(q), rank(i).0);
|
||||
if best.is_none_or(|(b, bk, _)| d < b || (d == b && k < bk)) {
|
||||
best = Some((d, k, i));
|
||||
}
|
||||
}
|
||||
if let Some((_, _, i)) = best {
|
||||
return i as f64;
|
||||
}
|
||||
let tol = (r.width() + r.height()).max(1e-6) * 1e-9;
|
||||
let nearest = segs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (c, _))| (c.nearest(q, tol), i))
|
||||
.min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq).then(rank(a.1).1.cmp(&rank(b.1).1)));
|
||||
let Some((near, i)) = nearest else { return 0.0 };
|
||||
if near.t > CORNER_END_SNAP && near.t < 1.0 - CORNER_END_SNAP {
|
||||
i as f64 + near.t
|
||||
} else if near.t < 0.5 {
|
||||
i as f64
|
||||
} else {
|
||||
((i + 1) % n) as f64
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1033,7 +1288,7 @@ pub(super) fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -
|
||||
let (rows, cols) = (*rows as usize, *cols as usize);
|
||||
Box::new(move |u: f64, v: f64| grid_eval(rows, cols, points, u, v))
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => match Coons::from_path(path) {
|
||||
EnvelopeKind::TopObject { path, corners } => match Coons::from_top_object(path, *corners) {
|
||||
Some(co) => Box::new(move |u: f64, v: f64| co.eval(u, v)),
|
||||
None => Box::new(flat),
|
||||
},
|
||||
|
||||
@@ -27,6 +27,10 @@ pub struct ObjectAttributes {
|
||||
/// the element's event attributes; nothing in VectorCraft runs them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub events: Vec<(String, String)>,
|
||||
/// The CSS classes the object had in an imported SVG, written back to `class` on export
|
||||
/// (beside the generated `cls-N` classes).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub classes: Vec<String>,
|
||||
/// Attributes in other applications' XML namespaces, in order, kept from SVG import to SVG
|
||||
/// export: what another tool notes on an object (a plotter's pen, a cutter's passes) survives
|
||||
/// a round trip through VectorCraft. Nothing in VectorCraft reads them. They are the object's,
|
||||
|
||||
@@ -69,6 +69,9 @@ pub struct NodeExtras {
|
||||
/// As an envelope with margins in Edit Contents, the margins its strokes gave when Edit Contents
|
||||
/// began ([`crate::live::EnvelopeOptions::bounds_margin`]).
|
||||
pub envelope_edit_margin: Option<[f32; 4]>,
|
||||
/// Transform panel › Align to Pixel Grid: the path's or compound path's horizontal and vertical
|
||||
/// segments stay on the pixel grid when it is transformed.
|
||||
pub pixel_aligned: bool,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -95,6 +98,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
shape_mode: crate::ShapeMode::Add,
|
||||
symbol_overrides: Vec::new(),
|
||||
envelope_edit_margin: None,
|
||||
pixel_aligned: false,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
@@ -448,6 +448,9 @@ impl Node {
|
||||
if self.appearance.gradients().next().is_some() {
|
||||
self.appearance.transform_gradients(a);
|
||||
}
|
||||
if self.appearance.has_svg_filter() {
|
||||
self.appearance.transform_svg_filters(a);
|
||||
}
|
||||
if sc.patterns {
|
||||
crate::pattern::transform_pattern_paints(self, a);
|
||||
}
|
||||
@@ -508,7 +511,7 @@ impl Node {
|
||||
*h = (lin * h.to_point()).to_vec2();
|
||||
}
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => path.transform(a),
|
||||
EnvelopeKind::TopObject { path, .. } => path.transform(a),
|
||||
EnvelopeKind::Warp { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ fn extras_are_written_flat_in_order() {
|
||||
e.compound_shape = true;
|
||||
e.shape_mode = crate::ShapeMode::Exclude;
|
||||
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
|
||||
e.pixel_aligned = true;
|
||||
}
|
||||
/// The top-level keys of a JSON object, in the order written.
|
||||
struct Keys(Vec<String>);
|
||||
@@ -67,9 +68,11 @@ fn extras_are_written_flat_in_order() {
|
||||
"compound_shape",
|
||||
"shape_mode",
|
||||
"envelope_edit_margin",
|
||||
"pixel_aligned",
|
||||
];
|
||||
assert_eq!(keys, order);
|
||||
assert_eq!(v["shape_mode"], "exclude");
|
||||
assert_eq!(v["pixel_aligned"], true);
|
||||
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
|
||||
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
|
||||
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
|
||||
|
||||
@@ -54,6 +54,7 @@ impl Serialize for Node {
|
||||
is_default(&e.shape_mode),
|
||||
e.symbol_overrides.is_empty(),
|
||||
e.envelope_edit_margin.is_none(),
|
||||
is_default(&e.pixel_aligned),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -96,6 +97,7 @@ impl Serialize for Node {
|
||||
field!("shape_mode", &e.shape_mode);
|
||||
field!("symbol_overrides", &e.symbol_overrides);
|
||||
field!("envelope_edit_margin", &e.envelope_edit_margin);
|
||||
field!("pixel_aligned", &e.pixel_aligned);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -236,6 +238,8 @@ pub(super) struct NodeWire {
|
||||
symbol_overrides: Vec<crate::SymbolOverride>,
|
||||
#[serde(default)]
|
||||
envelope_edit_margin: Option<[f32; 4]>,
|
||||
#[serde(default)]
|
||||
pixel_aligned: bool,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
@@ -263,6 +267,7 @@ impl From<NodeWire> for Node {
|
||||
shape_mode: w.shape_mode,
|
||||
symbol_overrides: w.symbol_overrides,
|
||||
envelope_edit_margin: w.envelope_edit_margin,
|
||||
pixel_aligned: w.pixel_aligned,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -126,6 +126,23 @@ impl SavedSelection {
|
||||
}
|
||||
}
|
||||
|
||||
/// An SVG filter the document holds (Effect › SVG Filters): a `<filter>` element named by its
|
||||
/// `id`, listed in the SVG Filters submenu and in Apply SVG Filter.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SvgFilter {
|
||||
/// The filter element's `id`.
|
||||
pub name: String,
|
||||
/// The `<filter>` element's XML, as it was written.
|
||||
pub xml: String,
|
||||
}
|
||||
|
||||
impl SvgFilter {
|
||||
/// Most SVG filters a document holds.
|
||||
pub const MAX: usize = 64;
|
||||
/// Longest filter element, in bytes.
|
||||
pub const MAX_XML: usize = 64 * 1024;
|
||||
}
|
||||
|
||||
/// A symbol definition.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Symbol {
|
||||
|
||||
@@ -54,6 +54,20 @@ pub struct Selection {
|
||||
/// the engine then sets the document's from it. Editing state, never saved.
|
||||
#[serde(skip)]
|
||||
pub new_art: Arc<HashSet<NodeId>>,
|
||||
/// An object of a dynamic symbol instance's art, selected with Direct Selection: the instance
|
||||
/// is the one selected object, and solid fill and stroke changes go to its own appearance for
|
||||
/// that object ([`crate::symbol_overrides`]). Any other selection change clears it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub symbol_part: Option<SymbolPart>,
|
||||
}
|
||||
|
||||
/// See [`Selection::symbol_part`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SymbolPart {
|
||||
/// The symbol instance.
|
||||
pub instance: NodeId,
|
||||
/// The object in the symbol's art, as [`crate::symbol_overrides::part`] names it.
|
||||
pub path: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
@@ -79,6 +93,13 @@ impl Selection {
|
||||
self.slices.clear();
|
||||
self.guides.clear();
|
||||
self.key_guide = None;
|
||||
self.symbol_part = None;
|
||||
}
|
||||
/// Select only instance `instance`, with the object at `path` of its symbol's art (see
|
||||
/// [`Selection::symbol_part`]).
|
||||
pub fn set_symbol_part(&mut self, instance: NodeId, path: Vec<u32>) {
|
||||
self.set([instance]);
|
||||
self.symbol_part = Some(SymbolPart { instance, path });
|
||||
}
|
||||
/// Is there a key for Align: an object or a guide?
|
||||
pub fn has_key(&self) -> bool {
|
||||
@@ -93,6 +114,7 @@ impl Selection {
|
||||
pub fn add(&mut self, id: NodeId) {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
if !self.objects.contains(&id) {
|
||||
self.objects.push(id);
|
||||
}
|
||||
@@ -100,6 +122,7 @@ impl Selection {
|
||||
pub fn remove(&mut self, id: NodeId) {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.objects.retain(|x| *x != id);
|
||||
self.anchors.remove(&id);
|
||||
self.segments.remove(&id);
|
||||
@@ -128,6 +151,7 @@ impl Selection {
|
||||
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
|
||||
/// Shift-click on a guide).
|
||||
pub fn toggle_guide(&mut self, i: usize) {
|
||||
self.symbol_part = None;
|
||||
if let Some(k) = self.guides.iter().position(|g| *g == i) {
|
||||
self.guides.remove(k);
|
||||
if self.key_guide == Some(i) {
|
||||
@@ -207,6 +231,27 @@ impl Selection {
|
||||
if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) {
|
||||
self.key_guide = None;
|
||||
}
|
||||
// A selected part needs its instance selected alone, with no guides, its symbol dynamic
|
||||
// and the object still in the symbol's art as a path, compound path or type, where neither
|
||||
// it nor a group or layer around it is hidden, locked or a template.
|
||||
let editable_part = |art: &crate::Node, path: &[u32]| {
|
||||
crate::symbol_overrides::part(art, path).is_some_and(crate::symbol_overrides::takes_part_paint)
|
||||
&& (0..=path.len())
|
||||
.all(|k| crate::symbol_overrides::part(art, &path[..k]).is_some_and(|n| n.visible && !n.locked && !n.is_template()))
|
||||
};
|
||||
let part_kept = self.symbol_part.as_ref().is_some_and(|sp| {
|
||||
self.objects == [sp.instance]
|
||||
&& self.guides.is_empty()
|
||||
&& found.get(&sp.instance).and_then(|p| doc.node_at(p)).is_some_and(|n| match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
doc.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| s.dynamic && editable_part(&s.art, &sp.path))
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
if !part_kept {
|
||||
self.symbol_part = None;
|
||||
}
|
||||
}
|
||||
/// Deselect the objects that are hidden or locked, themselves or through a group or layer
|
||||
/// around them (and so the key object when it is one): hidden or locked art can't stay
|
||||
@@ -238,6 +283,9 @@ impl Selection {
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
if self.symbol_part.as_ref().is_some_and(|sp| gone.contains(&sp.instance)) {
|
||||
self.symbol_part = None;
|
||||
}
|
||||
self.objects.retain(|o| !gone.contains(o));
|
||||
self.anchors.retain(|id, _| !gone.contains(id));
|
||||
self.segments.retain(|id, _| !gone.contains(id));
|
||||
|
||||
@@ -41,6 +41,82 @@ fn guides_are_selected_on_their_own() {
|
||||
assert_eq!(s.guides, vec![0]);
|
||||
}
|
||||
|
||||
/// A picked object of a dynamic symbol's instance stays picked while it and the groups and layers
|
||||
/// around it in the symbol's art are visible, unlocked and not a template. An art edit that hides
|
||||
/// or locks it, or one around it, or makes a layer around it a template, drops the pick.
|
||||
#[test]
|
||||
fn a_picked_symbol_part_is_dropped_once_it_cannot_be_edited() {
|
||||
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let leaf = Node::path(d.alloc_id(), rect(), crate::Appearance::default_art());
|
||||
let group = Node::group(d.alloc_id(), vec![Arc::new(leaf)]);
|
||||
let layer = Node::layer(d.alloc_id(), "Inner", crate::LayerColor::Preset(2));
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(group), Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Parts".into(), art: Arc::new(root.clone()) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Parts".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
// The layer in the art holds a path too.
|
||||
let in_layer = Node::path(d.alloc_id(), rect(), crate::Appearance::default_art());
|
||||
let mut art = root;
|
||||
if let Some(NodeKind::Layer { children, .. }) = art.children_mut().and_then(|c| c.get_mut(1)).map(|c| &mut Arc::make_mut(c).kind) {
|
||||
children.push(Arc::new(in_layer));
|
||||
}
|
||||
d.symbols[0].art = Arc::new(art.clone());
|
||||
let picked = |d: &Document, path: &[u32]| {
|
||||
let mut s = Selection::default();
|
||||
s.set_symbol_part(inst, path.to_vec());
|
||||
s.prune(d);
|
||||
s.symbol_part.is_some()
|
||||
};
|
||||
assert!(picked(&d, &[0, 0]) && picked(&d, &[1, 0]), "editable parts stay picked");
|
||||
assert!(!picked(&d, &[0]) && !picked(&d, &[1]) && !picked(&d, &[]), "a group or layer does not stay picked");
|
||||
let edited = |change: &dyn Fn(&mut Node)| {
|
||||
let mut d = d.clone();
|
||||
let mut art = art.clone();
|
||||
change(&mut art);
|
||||
d.symbols[0].art = Arc::new(art);
|
||||
d
|
||||
};
|
||||
let child = |art: &mut Node, path: &[usize]| -> Node {
|
||||
let mut n = &*art;
|
||||
for &i in path {
|
||||
n = &n.children().unwrap()[i];
|
||||
}
|
||||
n.clone()
|
||||
};
|
||||
let set = |art: &mut Node, path: &[usize], n: Node| {
|
||||
let mut at = art;
|
||||
for &i in path {
|
||||
at = Arc::make_mut(&mut at.children_mut().unwrap()[i]);
|
||||
}
|
||||
*at = n;
|
||||
};
|
||||
let hidden = edited(&|art| {
|
||||
let mut n = child(art, &[0, 0]);
|
||||
n.visible = false;
|
||||
set(art, &[0, 0], n);
|
||||
});
|
||||
assert!(!picked(&hidden, &[0, 0]), "the part is hidden");
|
||||
let locked_group = edited(&|art| {
|
||||
let mut n = child(art, &[0]);
|
||||
n.locked = true;
|
||||
set(art, &[0], n);
|
||||
});
|
||||
assert!(!picked(&locked_group, &[0, 0]), "the group around it is locked");
|
||||
assert!(picked(&locked_group, &[1, 0]), "a part outside the locked group stays");
|
||||
let template = edited(&|art| {
|
||||
let mut n = child(art, &[1]);
|
||||
if let NodeKind::Layer { template, .. } = &mut n.kind {
|
||||
*template = true;
|
||||
}
|
||||
set(art, &[1], n);
|
||||
});
|
||||
assert!(!picked(&template, &[1, 0]), "the layer around it is a template");
|
||||
let hidden_root = edited(&|art| art.visible = false);
|
||||
assert!(!picked(&hidden_root, &[0, 0]), "the art is hidden");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_show_and_lock_with_their_layer() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
|
||||
@@ -120,6 +120,21 @@ impl Quotes {
|
||||
prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '—' | '–') || quote_opened.unwrap_or_else(|| self.is_open(p)))
|
||||
}
|
||||
|
||||
/// The straight quote a typed curly quote stands for: `"` for `”` (U+201D) and nothing else.
|
||||
/// The macOS Serbian Cyrillic layout has no straight `"` and types `”` on Shift+2, so with
|
||||
/// Typographer's Quotes on, a `”` typed alone where a quote opens takes the document's opening
|
||||
/// quote ([`Quotes::opens_after`]); where a quote closes it stays `”`. `“ „` and the single
|
||||
/// quotes `‘ ’ ‚` stay as typed: that layout's apostrophe key already types `’`, as Serbian
|
||||
/// wants, and `’90s` keeps its apostrophe.
|
||||
pub fn typed_as_straight(c: char) -> Option<char> {
|
||||
(c == '”').then_some('"')
|
||||
}
|
||||
|
||||
/// Does a quote typed after `prev` (the character before it, `None` at the start) open?
|
||||
pub fn opens_after(&self, prev: Option<char>) -> bool {
|
||||
self.opens(prev, None)
|
||||
}
|
||||
|
||||
/// `text` with straight quotes (`"` and `'`) replaced by these quotes: opening or closing by
|
||||
/// context (an apostrophe is a closing single quote). `prev` is the character before `text`,
|
||||
/// and is updated to its last character, so text can be converted in pieces.
|
||||
@@ -420,6 +435,12 @@ mod tests {
|
||||
}
|
||||
let mut prev = None;
|
||||
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
|
||||
// Only a typed `”` stands for a straight quote; the other curly quotes stay as typed.
|
||||
assert_eq!(Quotes::typed_as_straight('”'), Some('"'));
|
||||
assert!(['“', '„', '‘', '’', '‚', '"', '\'', '«', '»', '「', 'a'].iter().all(|&c| Quotes::typed_as_straight(c).is_none()));
|
||||
// A quote opens at the start and after a space, and closes after a letter.
|
||||
assert!(Quotes::ENGLISH.opens_after(None) && Quotes::ENGLISH.opens_after(Some(' ')));
|
||||
assert!(!Quotes::ENGLISH.opens_after(Some('a')));
|
||||
// Bulgarian: „…“ at either level, as CLDR has it.
|
||||
let mut prev = None;
|
||||
assert_eq!(language_quotes("bulgarian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a „b“ c“");
|
||||
|
||||
+127
-3
@@ -7,6 +7,7 @@
|
||||
//! those links (and colours) wherever art and swatches hold them, copying only the nodes that
|
||||
//! change.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
@@ -85,6 +86,12 @@ impl Document {
|
||||
fn numbered_swatch_name(&self, base: &str, from: usize) -> String {
|
||||
(from..).map(|i| format!("{base} {i}")).find(|n| !self.swatch_name_taken(n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
/// Names for several new swatches: [`FreeSwatchNames::take`] gives what
|
||||
/// [`Document::free_swatch_name`] gives once the swatches named before it are added.
|
||||
pub fn free_swatch_names(&self) -> FreeSwatchNames {
|
||||
let taken = self.swatches_iter().map(|s| s.name.clone()).chain(self.swatch_groups.iter().map(|g| g.name.clone()));
|
||||
FreeSwatchNames { taken: taken.chain([REGISTRATION.to_string()]).collect(), next: HashMap::new() }
|
||||
}
|
||||
/// The name a new swatch of `paint` gets by default, unused in the document: a colour's values
|
||||
/// ([`color_name`], made free like [`Document::free_swatch_name`]), or "New Gradient Swatch 1",
|
||||
/// "New Pattern Swatch 1"…
|
||||
@@ -169,7 +176,7 @@ impl Document {
|
||||
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
|
||||
let mut tree = |n: &Node| {
|
||||
walk_with_masks(n, &mut |m| {
|
||||
node_paints(m).for_each(&mut *f);
|
||||
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
|
||||
if let NodeKind::Mesh(mesh) = &m.kind {
|
||||
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
|
||||
}
|
||||
@@ -200,6 +207,52 @@ pub fn color_name(c: Color) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatch and color group names of a document ([`Document::free_swatch_names`]) and the names
|
||||
/// handed out since, for naming many new swatches without searching the document for each name.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FreeSwatchNames {
|
||||
taken: HashSet<String>,
|
||||
/// For each base and first number already numbered, the number its next numbered name is
|
||||
/// looked for from: names are only ever added, so the numbers below it stay taken.
|
||||
next: HashMap<(String, usize), usize>,
|
||||
}
|
||||
|
||||
impl FreeSwatchNames {
|
||||
/// `base`, or the first of "base 2", "base 3"… not taken, as [`Document::free_swatch_name`]
|
||||
/// gives it; the name is taken from then on.
|
||||
pub fn take(&mut self, base: &str) -> String {
|
||||
let name = if self.taken.contains(base) { self.numbered(base, 2) } else { base.to_string() };
|
||||
self.taken.insert(name.clone());
|
||||
name
|
||||
}
|
||||
/// The name [`Document::new_swatch_name`] gives a new swatch of `paint`; the name is taken
|
||||
/// from then on.
|
||||
pub fn take_new(&mut self, paint: &Paint) -> String {
|
||||
let base = match paint {
|
||||
Paint::Solid { swatch: Some(n), tint, .. } if *tint < 1.0 => return self.take(&format!("{n} {}%", tint_percent(*tint))),
|
||||
Paint::Solid { color, .. } => return self.take(&color_name(*color)),
|
||||
Paint::Gradient(_) => "New Gradient Swatch",
|
||||
_ => "New Pattern Swatch",
|
||||
};
|
||||
let name = self.numbered(base, 1);
|
||||
self.taken.insert(name.clone());
|
||||
name
|
||||
}
|
||||
/// Count `name` as taken (a swatch or color group added another way).
|
||||
pub fn insert(&mut self, name: &str) {
|
||||
self.taken.insert(name.to_string());
|
||||
}
|
||||
/// The first of "base `from`", "base `from + 1`"… not taken.
|
||||
fn numbered(&mut self, base: &str, from: usize) -> String {
|
||||
let key = (base.to_string(), from);
|
||||
let start = self.next.get(&key).copied().unwrap_or(from);
|
||||
let (i, name) =
|
||||
(start..).map(|i| (i, format!("{base} {i}"))).find(|(_, n)| !self.taken.contains(n)).unwrap_or_else(|| (start, base.to_string()));
|
||||
self.next.insert(key, i + 1);
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Document::map_solid_paints`] applies to each linkable colour: `(colour, link, tint)`,
|
||||
/// true when it changed them.
|
||||
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
|
||||
@@ -222,10 +275,11 @@ fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key:
|
||||
}
|
||||
|
||||
/// Every colour in the subtree of `n` with the swatch it links to: solid fills, strokes, text runs
|
||||
/// and gradient stops (with their link), then mesh points (unlinked), in paint order.
|
||||
/// and gradient stops (with their link), a dynamic symbol instance's own paints
|
||||
/// ([`override_paints`]), then mesh points (unlinked), in paint order.
|
||||
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
|
||||
n.walk(&mut |m| {
|
||||
for p in node_paints(m) {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
|
||||
@@ -262,6 +316,12 @@ pub fn node_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])).chain(n.extras().colorize.as_deref())
|
||||
}
|
||||
|
||||
/// The paints a dynamic symbol instance keeps for objects of its art
|
||||
/// ([`crate::symbol_overrides`]), which [`node_paints`] leaves out.
|
||||
pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
|
||||
}
|
||||
|
||||
/// Mutable [`node_paints`], in the same order.
|
||||
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
|
||||
let runs = match &mut n.kind {
|
||||
@@ -300,6 +360,20 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
|
||||
}
|
||||
out = Some(m);
|
||||
}
|
||||
// A dynamic symbol instance's own paints for objects of its art (`symbol_overrides`).
|
||||
if !n.extras().symbol_overrides.is_empty() {
|
||||
let mut overrides = n.extras().symbol_overrides.clone();
|
||||
let mut k = 0;
|
||||
for p in overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
|
||||
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) && p.map_links(f) {
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
if k > 0 {
|
||||
out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides;
|
||||
count += k;
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children() {
|
||||
for (i, c) in ch.iter().enumerate() {
|
||||
if let Some((new, k)) = map_node(c, f) {
|
||||
@@ -419,6 +493,56 @@ mod tests {
|
||||
assert_eq!(d.new_swatch_name(&Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "R=255 G=0 B=0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_swatch_names_match_naming_each_swatch_as_it_is_added() {
|
||||
let (mut d, _, _) = doc();
|
||||
let mut names = d.free_swatch_names();
|
||||
for base in ["Brand", "Brand", "Mine", "Fresh", "Fresh", "Brand 2", "Brand", REGISTRATION, "Fresh 3", "Fresh", "Mine 2"] {
|
||||
let want = d.free_swatch_name(base);
|
||||
assert_eq!(names.take(base), want, "{base}");
|
||||
d.swatches.push(Swatch { name: want, paint: Paint::solid(Color::BLACK), global: false, spot: false });
|
||||
}
|
||||
let added: Vec<&str> = d.swatches.iter().rev().take(11).rev().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(
|
||||
added,
|
||||
["Brand 2", "Brand 3", "Mine 2", "Fresh", "Fresh 2", "Brand 2 2", "Brand 4", "[Registration] 2", "Fresh 3", "Fresh 4", "Mine 2 2"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_swatch_names_match_new_swatch_names_as_swatches_are_added() {
|
||||
let (mut d, _, _) = doc();
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
d.swatches.push(Swatch { name: "New Gradient Swatch 2".into(), paint: Paint::solid(red), global: false, spot: false });
|
||||
let mut names = d.free_swatch_names();
|
||||
// A name taken another way (a group made alongside) counts for both.
|
||||
names.insert("R=255 G=0 B=0 3");
|
||||
d.swatch_groups.push(SwatchGroup { name: "R=255 G=0 B=0 3".into(), swatches: vec![] });
|
||||
let tint = Paint::Solid { color: red, swatch: Some("Brand".into()), tint: 0.4 };
|
||||
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default())));
|
||||
let paints = [Paint::solid(red), Paint::solid(red), gradient.clone(), tint.clone(), Paint::solid(red), gradient.clone(), tint, gradient];
|
||||
let mut added = vec![];
|
||||
for paint in paints {
|
||||
let want = d.new_swatch_name(&paint);
|
||||
assert_eq!(names.take_new(&paint), want);
|
||||
d.swatches.push(Swatch { name: want.clone(), paint, global: false, spot: false });
|
||||
added.push(want);
|
||||
}
|
||||
assert_eq!(
|
||||
added,
|
||||
[
|
||||
"R=255 G=0 B=0",
|
||||
"R=255 G=0 B=0 2",
|
||||
"New Gradient Swatch 1",
|
||||
"Brand 40%",
|
||||
"R=255 G=0 B=0 4",
|
||||
"New Gradient Swatch 3",
|
||||
"Brand 40% 2",
|
||||
"New Gradient Swatch 4"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_copies_only_changed_nodes() {
|
||||
let (mut d, a, b) = doc();
|
||||
|
||||
@@ -451,6 +451,18 @@ impl NineSliceMap {
|
||||
self.most_at(art, &boxes, 0)
|
||||
}
|
||||
|
||||
/// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one
|
||||
/// piece, with everything in it: the map of the cell its box lies in, or of the cell at the
|
||||
/// origin when it has no box. `None` when its box crosses a guide.
|
||||
pub fn one_cell(&self, n: &Node, doc: &Document) -> Option<Affine> {
|
||||
let boxes = doc.symbol_boxes().quick();
|
||||
let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
|
||||
return Some(self.cell_at(Point::ZERO));
|
||||
};
|
||||
let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1));
|
||||
(cols[0] == cols[1] && rows[0] == rows[1]).then(|| self.cell_xf(cols[0], rows[0]))
|
||||
}
|
||||
|
||||
/// [`Self::most_placed`] for [`Self::place_unclipped`]: the most objects it makes of `art`.
|
||||
pub fn most_placed_unclipped(&self, art: &Node, doc: &Document) -> u64 {
|
||||
Self { clips: false, ..*self }.most_placed(art, doc)
|
||||
|
||||
@@ -49,6 +49,10 @@ impl SymbolOverride {
|
||||
r.style.fill = p.clone();
|
||||
}
|
||||
if let Some(p) = &self.stroke {
|
||||
// A painted stroke on characters without a weight gets 1 pt, as a path's does.
|
||||
if !p.is_none() && r.style.stroke_width == 0.0 {
|
||||
r.style.stroke_width = 1.0;
|
||||
}
|
||||
r.style.stroke = p.clone();
|
||||
}
|
||||
}
|
||||
@@ -57,6 +61,14 @@ impl SymbolOverride {
|
||||
n.appearance.set_fill(p.clone());
|
||||
}
|
||||
if let Some(p) = &self.stroke {
|
||||
// A stroke without paint has no weight; painting it gives it 1 pt.
|
||||
if !p.is_none()
|
||||
&& let Some(s) = n.appearance.stroke_mut()
|
||||
&& s.paint.is_none()
|
||||
&& s.width == 0.0
|
||||
{
|
||||
s.width = 1.0;
|
||||
}
|
||||
n.appearance.set_stroke(p.clone());
|
||||
}
|
||||
}
|
||||
@@ -69,6 +81,13 @@ impl SymbolOverride {
|
||||
}
|
||||
}
|
||||
|
||||
/// Can Direct Selection select `n`, an object of a dynamic symbol's art, and change its fill and
|
||||
/// stroke for one instance? Paths, compound paths and type can; groups, images and every other
|
||||
/// object cannot.
|
||||
pub fn takes_part_paint(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_))
|
||||
}
|
||||
|
||||
/// An override's path read from a file: at most [`MAX_PATH_DEPTH`] indices, so a compressed file
|
||||
/// of one endless path stays small once read.
|
||||
fn short_path<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> {
|
||||
@@ -180,6 +199,27 @@ mod tests {
|
||||
assert_eq!(kept.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_on_type_without_a_weight_gets_one_point() {
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let style = crate::CharStyle { stroke: Paint::None, stroke_width: 0.0, ..crate::CharStyle::default() };
|
||||
let text = Node::new(NodeId(2), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::ZERO, "Hi", style))));
|
||||
let mut a = Node::group(NodeId(1), vec![Arc::new(text)]);
|
||||
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
|
||||
let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") };
|
||||
assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt");
|
||||
|
||||
// A path whose stroke has neither paint nor weight gets 1 pt too.
|
||||
let mut ap = Appearance::default_art();
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
(s.paint, s.width) = (Paint::None, 0.0);
|
||||
}
|
||||
let path = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), ap);
|
||||
let mut a = Node::group(NodeId(1), vec![Arc::new(path)]);
|
||||
apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]);
|
||||
assert_eq!(part(&a, &[0]).unwrap().appearance.stroke_width(), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_deeper_than_the_cap_does_not_read() {
|
||||
let deep = format!("{{\"path\":{:?}}}", vec![0; MAX_PATH_DEPTH + 1]);
|
||||
|
||||
@@ -228,7 +228,8 @@ pub struct ParaStyle {
|
||||
pub leading_model: LeadingModel,
|
||||
/// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line
|
||||
/// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
|
||||
/// it and imported text keep [`Burasagari::None`].
|
||||
/// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding
|
||||
/// punctuation on, which opens with [`Burasagari::Forced`].
|
||||
pub burasagari: Burasagari,
|
||||
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
|
||||
/// line.
|
||||
|
||||
@@ -233,13 +233,16 @@ impl ParaList {
|
||||
|
||||
/// The list that the Type tool starts when `typed` and a space are typed at the start of a
|
||||
/// paragraph: "1." or "1)" starts a numbered list in 1, 2, 3, "A." or "A)" starts one in A, B,
|
||||
/// C, and "*", "#", ">" or "+" starts a bulleted list with the filled dot. Any other text starts
|
||||
/// none.
|
||||
/// C, and "*" starts a bulleted list with the filled dot, "+" one with the hollow circle, "#"
|
||||
/// one with the filled square and ">" one with the dash. Any other text starts none.
|
||||
pub fn typed(typed: &str) -> Option<ParaList> {
|
||||
match typed {
|
||||
"1." | "1)" => Some(Self::numbered(NumberStyle::Arabic)),
|
||||
"A." | "A)" => Some(Self::numbered(NumberStyle::UpperLetters)),
|
||||
"*" | "#" | ">" | "+" => Some(Self::bulleted(Bullet::Dot)),
|
||||
"*" => Some(Self::bulleted(Bullet::Dot)),
|
||||
"+" => Some(Self::bulleted(Bullet::Circle)),
|
||||
"#" => Some(Self::bulleted(Bullet::Square)),
|
||||
">" => Some(Self::bulleted(Bullet::Dash)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,22 +212,23 @@ fn number_styles_write_their_numbers_and_roll_over() {
|
||||
}
|
||||
|
||||
/// Typed list detection: "1.", "1)", "A." and "A)" and a space at the start of a paragraph
|
||||
/// start a numbered list, and "*", "#", ">" and "+" and a space start a bulleted list with the
|
||||
/// filled dot. Other text, the same characters later in a paragraph or without the space, and
|
||||
/// a paragraph already in a list start nothing.
|
||||
/// start a numbered list, and "*", "+", "#" and ">" and a space start a bulleted list with the
|
||||
/// filled dot, the hollow circle, the filled square and the dash. Other text, the same characters
|
||||
/// later in a paragraph or without the space, and a paragraph already in a list start nothing.
|
||||
#[test]
|
||||
fn typed_list_starts_are_found_at_a_paragraphs_start() {
|
||||
let (arabic, letters, dot) =
|
||||
(ParaList::numbered(NumberStyle::Arabic), ParaList::numbered(NumberStyle::UpperLetters), ParaList::bulleted(Bullet::Dot));
|
||||
let typed = ["1.", "1)", "A.", "A)", "*", "#", ">", "+"].map(ParaList::typed);
|
||||
assert_eq!(typed, [arabic, arabic, letters, letters, dot, dot, dot, dot].map(Some));
|
||||
let (circle, square, dash) = (ParaList::bulleted(Bullet::Circle), ParaList::bulleted(Bullet::Square), ParaList::bulleted(Bullet::Dash));
|
||||
let typed = ["1.", "1)", "A.", "A)", "*", "+", "#", ">"].map(ParaList::typed);
|
||||
assert_eq!(typed, [arabic, arabic, letters, letters, dot, circle, square, dash].map(Some));
|
||||
for other in ["", "2.", "a.", "a)", "I.", "1", "A", "1:", "-", "•", "1.)", " 1.", "*1", "1."] {
|
||||
assert_eq!(ParaList::typed(other), None, "{other:?}");
|
||||
}
|
||||
let mut t = TextObject::point(Point::ZERO, "Fruit\n1. Apples\nA) x * y\n+ ", CharStyle::default());
|
||||
assert_eq!(t.typed_list_at(9), Some((6, arabic)));
|
||||
assert_eq!(t.typed_list_at(19), Some((16, letters)));
|
||||
assert_eq!(t.typed_list_at(27), Some((25, dot)));
|
||||
assert_eq!(t.typed_list_at(27), Some((25, circle)));
|
||||
// Not at the paragraph's start, not right after the space, or past the end.
|
||||
for at in [0, 5, 8, 10, 15, 23, 25, 26, 99] {
|
||||
assert_eq!(t.typed_list_at(at), None, "{at}");
|
||||
@@ -245,7 +246,7 @@ fn typed_list_starts_are_found_at_a_paragraphs_start() {
|
||||
#[test]
|
||||
fn typed_list_starts_skip_a_continued_paragraph() {
|
||||
let dot = ParaList::bulleted(Bullet::Dot);
|
||||
let mut t = TextObject::point(Point::ZERO, "* Pears\n# ", CharStyle::default());
|
||||
let mut t = TextObject::point(Point::ZERO, "* Pears\n* ", CharStyle::default());
|
||||
assert_eq!(t.typed_list_at(2), Some((0, dot)));
|
||||
t.first_para_continues = true;
|
||||
assert_eq!(t.typed_list_at(2), None, "a continued paragraph starts no list");
|
||||
|
||||
@@ -105,12 +105,11 @@ impl DataSet {
|
||||
/// The variable state of a document: definitions, datasets, bindings
|
||||
/// (object id → the variables bound to it) and which dataset is active.
|
||||
///
|
||||
/// An object may be driven by several variables — the reference app binds the selected object
|
||||
/// to the selected variable, one click at a time, and never says a second binding replaces the
|
||||
/// first — so a binding is a set. `dataset.select` applies the text values in the order the
|
||||
/// variables are defined, which is what makes two text variables on one object deterministic:
|
||||
/// the last one wins, and `applied` counts both. Of two visibility variables on one object, the
|
||||
/// last one defined wins too.
|
||||
/// An object may be driven by several variables, so a binding is a set. `variable.bind` and Make
|
||||
/// Text Dynamic refuse a second text variable on one type object, but a document saved before
|
||||
/// they did may hold two: `dataset.select` applies the text values in the order the variables
|
||||
/// are defined, so the last one wins, and `applied` counts both. Of two visibility variables on
|
||||
/// one object, the last one defined wins too.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Variables {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
|
||||
@@ -17,6 +17,11 @@ vectorcraft-text = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
image = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
|
||||
# workspace reads SVG with; raster-images decodes the object's pixels it hands the filter as a PNG.
|
||||
resvg = { version = "0.48", default-features = false, features = ["raster-images"] }
|
||||
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
|
||||
svgtypes = "0.16"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -105,6 +105,8 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"sketch.waterPaper" => always(&["fiberLength"]),
|
||||
TRAP => always(&["thickness", "precision"]),
|
||||
RASTERIZE => always(&["addAround"]),
|
||||
// The points one unit of the filter measures.
|
||||
crate::SVG_FILTER => always(&["scale"]),
|
||||
_ => Lengths::default(),
|
||||
}
|
||||
}
|
||||
@@ -825,6 +827,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{colorModel: \"document\" (the document's mode, RGB or CMYK)|\"grayscale\"|\"bitmap\" (\"document\"), useDocumentResolution: bool (true: Document Raster Effects Settings › Resolution), resolution: ppi 1..2400 (72; with useDocumentResolution false), background: \"white\"|\"transparent\" (\"transparent\"), antiAlias: \"none\"|\"art\"|\"type\" (\"art\"; none: hard edges), clippingMask: bool (false; the image clipped to the art's outline), addAround: pt 0..1000 (0; room around the art)} draws the object as an image of square pixels over its bounds and the room around them, leaving its paths, type and other art as they are; when it is the object's only raster effect, Expand Appearance makes the image Object › Rasterize makes",
|
||||
json!({"colorModel": "document", "useDocumentResolution": true, "resolution": 72.0, "background": "transparent", "antiAlias": "art", "clippingMask": false, "addAround": 0.0}),
|
||||
));
|
||||
v.push(r(
|
||||
crate::SVG_FILTER,
|
||||
"SVG Filter",
|
||||
&["Effect", "SVG Filters"],
|
||||
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
|
||||
json!({"scale": 1.0, "origin": [0.0, 0.0]}),
|
||||
));
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! Warp) rewrite a path: [`apply_geometry`] evaluates them in stack order.
|
||||
//! - **Raster effects** (Drop Shadow, Inner/Outer Glow, Feather, Gaussian Blur, Rasterize, and the
|
||||
//! Photoshop-style filters of [`pixel`]: Radial Blur, Smart Blur, Color Halftone, Crystallize, Mezzotint, Pointillize, Halftone Pattern,
|
||||
//! Unsharp Mask and Glowing Edges) are described by
|
||||
//! Unsharp Mask and Glowing Edges, and the SVG filters of [`svg_filter`]) are described by
|
||||
//! [`raster_effects`] and painted by the renderer; [`outset`] says how far they reach beyond
|
||||
//! the geometry.
|
||||
//! - **Stroke geometry** ([`stroke`]): arrowheads, dash patterns and width profiles, shared by the
|
||||
@@ -52,6 +52,7 @@ mod revolve;
|
||||
mod solids;
|
||||
pub mod stroke;
|
||||
mod stylize;
|
||||
pub mod svg_filter;
|
||||
pub mod trap;
|
||||
mod util;
|
||||
mod warp;
|
||||
@@ -84,11 +85,13 @@ pub use reshape::{
|
||||
};
|
||||
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
|
||||
pub use solids::{
|
||||
EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, extrude_options, has_solid, inflate_options, is_three_d, solid_art, validate_solid,
|
||||
validate_three_d, view_options,
|
||||
EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, SolidMesh, THREE_D_TYPES, extrude_options, has_solid, inflate_options, is_three_d, solid_art,
|
||||
three_d_meshes, three_d_params_as, validate_solid, validate_three_d, view_options,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
pub use trap::TRAP;
|
||||
pub use vectorcraft_three_d::Mesh;
|
||||
pub use warp::{WarpStyle, warp_point};
|
||||
|
||||
mod catalog;
|
||||
|
||||
@@ -39,6 +39,8 @@ pub fn outline_object(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
/// Run `f` with the hooks live evaluation needs; symbols and patterns come from `doc` (without a
|
||||
/// document, symbol instances and pattern tiles stay as they are).
|
||||
fn with_hooks<R>(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R {
|
||||
// Envelopes map type from its glyphs here too, without an engine session.
|
||||
vectorcraft_text::register_envelope_ink();
|
||||
let outline = |n: &Node| outline_object(doc, n);
|
||||
let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region));
|
||||
f(Hooks { outline: Some(&outline), appearance: Some(&bake_appearance), pattern: Some(&tiles), symbols: doc })
|
||||
|
||||
@@ -119,6 +119,7 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
pub fn is_raster(id: &str) -> bool {
|
||||
matches!(id, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "blur.gaussian" | RASTERIZE)
|
||||
|| PIXEL_EFFECTS.contains(&id)
|
||||
|| id == crate::SVG_FILTER
|
||||
}
|
||||
|
||||
/// Does `id` change geometry? (Crop Marks and Vector Halftone add art of their own instead,
|
||||
|
||||
@@ -287,6 +287,8 @@ pub enum PixelFx {
|
||||
DeInterlace { even: bool, interpolate: bool },
|
||||
/// Video › NTSC Colors: colours a television signal can't carry made less saturated.
|
||||
NtscColors,
|
||||
/// Effect › SVG Filters: an SVG `<filter>` element run on the pixels.
|
||||
Svg(crate::svg_filter::SvgFilterFx),
|
||||
}
|
||||
|
||||
/// What a raster's colour channels hold, for the filters that treat them apart (Color Halftone
|
||||
@@ -598,6 +600,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
interpolate: text(p, "create", "duplication").eq_ignore_ascii_case("interpolation"),
|
||||
},
|
||||
"video.ntscColors" => PixelFx::NtscColors,
|
||||
crate::SVG_FILTER => PixelFx::Svg(crate::svg_filter::SvgFilterFx::parse(p)?),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -666,6 +669,7 @@ impl PixelFx {
|
||||
PixelFx::Crystallize { cell } | PixelFx::Pointillize { cell } | PixelFx::StainedGlass { cell, .. } => 1.5 * cell,
|
||||
// A square whose centre is on the object is drawn whole.
|
||||
PixelFx::Patchwork { square, .. } => square.max(1.0),
|
||||
PixelFx::Svg(ref f) => f.outset(bounds),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -745,12 +749,17 @@ impl PixelFx {
|
||||
// The lines above and below.
|
||||
PixelFx::DeInterlace { .. } => Some(video::MAX_LINE),
|
||||
PixelFx::NtscColors => Some(0.0),
|
||||
// A filter's object bounding box is the whole object's.
|
||||
PixelFx::Svg(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the effect on `data`, `w` × `h` premultiplied RGBA8 pixels lying in the document as
|
||||
/// `space` says. Does nothing when the sizes don't match.
|
||||
pub fn apply(&self, data: &mut [u8], w: usize, h: usize, space: &PixelSpace) {
|
||||
if let PixelFx::Svg(f) = self {
|
||||
return f.apply(data, w, h, space);
|
||||
}
|
||||
let Some(px) = pixels(data, w, h) else { return };
|
||||
let to_px = |len: f64| len / space.px.max(1e-9);
|
||||
match *self {
|
||||
@@ -829,6 +838,7 @@ impl PixelFx {
|
||||
}
|
||||
PixelFx::DeInterlace { even, interpolate } => video::deinterlace(px, w, h, space, even, interpolate),
|
||||
PixelFx::NtscColors => video::ntsc(px),
|
||||
PixelFx::Svg(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,6 +226,45 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
|
||||
art(n, true)
|
||||
}
|
||||
|
||||
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
|
||||
/// the object, one in its top visible fill (else its stroke); with it on fills and strokes, one for
|
||||
/// each of them.
|
||||
pub(crate) fn revolve_meshes(n: &Node) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let path = profile(n).ok_or("Revolve currently requires a path or compound path")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
|
||||
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let mesh = vectorcraft_three_d::revolve_mesh(path, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?;
|
||||
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
|
||||
};
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) {
|
||||
let before = n.appearance.effects.get(..index).unwrap_or_default();
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
|
||||
let path = geometry(&path, before, &ctx);
|
||||
let item = n
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i))
|
||||
.or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))
|
||||
.ok_or("the revolved object has no fill or stroke")?;
|
||||
return Ok(vec![mesh(&path, fx, item)?]);
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE)
|
||||
&& let Some(fx) = item.effects().get(index)
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
out.push(mesh(&p, fx, item)?);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn art(n: &Node, expand: bool) -> Option<Node> {
|
||||
if !has_revolve(n) {
|
||||
return None;
|
||||
|
||||
+207
-23
@@ -6,7 +6,7 @@ use serde_json::Value;
|
||||
use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, View};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
|
||||
|
||||
#[cfg(test)]
|
||||
use vectorcraft_doc::color::Color;
|
||||
@@ -25,6 +25,32 @@ pub fn is_three_d(id: &str) -> bool {
|
||||
id == crate::REVOLVE || SOLIDS.contains(&id)
|
||||
}
|
||||
|
||||
/// The 3D and Materials panel's object types and the effect that draws each: (type, effect id).
|
||||
/// Plane keeps the art flat, which is what Rotate draws.
|
||||
pub const THREE_D_TYPES: [(&str, &str); 4] = [("plane", ROTATE), ("extrude", EXTRUDE), ("revolve", crate::REVOLVE), ("inflate", INFLATE)];
|
||||
|
||||
/// The parameters of 3D effect `to` for an effect `from` with `params`, as switching the object
|
||||
/// type keeps them: every setting `to` takes keeps its value from `params` (the defaults of `from`
|
||||
/// under them), each rotation angle wrapped into -180° to 180° when `to` is not Revolve, and the
|
||||
/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped.
|
||||
pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
|
||||
let current = crate::merged_params(from, params);
|
||||
let mut out = crate::default_params(to).and_then(|v| v.as_object().cloned()).unwrap_or_default();
|
||||
for (key, value) in out.iter_mut() {
|
||||
if let Some(v) = current.get(key) {
|
||||
value.clone_from(v);
|
||||
}
|
||||
}
|
||||
if to != crate::REVOLVE {
|
||||
for key in ["rotationX", "rotationY", "rotationZ"] {
|
||||
if let Some(a) = out.get(key).and_then(Value::as_f64).filter(|a| !(-180.0..=180.0).contains(a)) {
|
||||
out.insert(key.into(), serde_json::json!((a + 180.0).rem_euclid(360.0) - 180.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
fn solid(fx: &[Effect]) -> Option<(usize, &Effect)> {
|
||||
fx.iter().enumerate().find(|(_, e)| e.visible && SOLIDS.contains(&e.id.as_str()))
|
||||
}
|
||||
@@ -195,6 +221,10 @@ fn union_bounds(shapes: &[Profile]) -> Option<Rect> {
|
||||
/// The most members a 3D effect on a group builds solids from.
|
||||
const MAX_MEMBERS: usize = 4096;
|
||||
|
||||
/// The most triangles the meshes of one 3D effect hold together (about 290 MB of corners and
|
||||
/// normals): past it the object is too complex to export.
|
||||
const MAX_MESH_TRIANGLES: usize = 2_000_000;
|
||||
|
||||
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
|
||||
/// compound path and type in it, at any depth of its groups, each through its own geometry
|
||||
/// effects and painted with its own fills and strokes. Like the effect on a group in the
|
||||
@@ -312,6 +342,38 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
|
||||
/// a group's members from the back up, each with its shape's opacity and the region it paints.
|
||||
/// The solids share the bounds of all their parts (`fallback` when none has any): one center to
|
||||
/// turn, twist and taper about, and Inflate's grid reaches over the strokes' outlines.
|
||||
fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<(&AppearanceItem, f32, PathData, FillRule)>, Rect) {
|
||||
let parts: Vec<(&AppearanceItem, f32, PathData, FillRule)> = shapes
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| {
|
||||
let (area, rule) = region(&s.path, s.rule, i);
|
||||
(i, s.opacity, area, rule)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let bounds = parts.iter().filter_map(|(_, _, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(fallback);
|
||||
(parts, bounds)
|
||||
}
|
||||
|
||||
/// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before`
|
||||
/// its 3D effect, about the bounds of all of them.
|
||||
fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) {
|
||||
if before.iter().any(|e| e.visible && is_geometry(&e.id))
|
||||
&& let Some(b) = union_bounds(shapes)
|
||||
{
|
||||
let ctx = GeomContext::of(n);
|
||||
for s in shapes {
|
||||
s.path = apply_geometry_with(before, &s.path, b, &ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D art of one effect `fx` on `path` (already through the effects before it).
|
||||
/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a
|
||||
/// solid from the path for the top visible fill and one from the outline of each visible stroke,
|
||||
@@ -337,20 +399,7 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
|
||||
}
|
||||
return Some(out);
|
||||
}
|
||||
// Each shape's top fill and its strokes, a group's members from the back up.
|
||||
let parts: Vec<(&AppearanceItem, f32, PathData, FillRule)> = shapes
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| {
|
||||
let (area, rule) = region(&s.path, s.rule, i);
|
||||
(i, s.opacity, area, rule)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// The solids share the bounds of all their shapes: one center to turn, twist and taper about,
|
||||
// and Inflate's grid reaches over the strokes' outlines.
|
||||
let bounds = parts.iter().filter_map(|(_, _, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(b);
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let built = if fx.id == INFLATE {
|
||||
// One eye for every puff, as far away as the highest needs.
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
|
||||
@@ -467,14 +516,7 @@ pub fn solid_art(n: &Node) -> Option<Node> {
|
||||
fn group_solid_art(n: &Node) -> Option<Node> {
|
||||
let (index, fx) = solid(&n.appearance.effects)?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
let before = n.appearance.effects.get(..index)?;
|
||||
if before.iter().any(|e| e.visible && is_geometry(&e.id)) {
|
||||
let b = union_bounds(&shapes)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
for s in &mut shapes {
|
||||
s.path = apply_geometry_with(before, &s.path, b, &ctx);
|
||||
}
|
||||
}
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let children = art_for(n, fx, &shapes)?;
|
||||
let remaining =
|
||||
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
|
||||
@@ -484,5 +526,147 @@ fn group_solid_art(n: &Node) -> Option<Node> {
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// One solid of a 3D object as a mesh, with the color it is painted.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SolidMesh {
|
||||
pub mesh: Mesh,
|
||||
/// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray
|
||||
/// for a pattern.
|
||||
pub color: [f32; 4],
|
||||
}
|
||||
|
||||
/// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]).
|
||||
pub(crate) fn mesh_color(paint: &Paint, opacity: f32) -> [f32; 4] {
|
||||
let (rgb, alpha) = match paint {
|
||||
Paint::Solid { color, .. } => (color.to_rgb(), 1.0),
|
||||
Paint::Gradient(g) if !g.gradient.stops.is_empty() => {
|
||||
let n = g.gradient.stops.len() as f32;
|
||||
let mut sum = [0.0f32; 4];
|
||||
for s in &g.gradient.stops {
|
||||
let [r, gr, b] = s.color.to_rgb();
|
||||
sum = [sum[0] + r, sum[1] + gr, sum[2] + b, sum[3] + s.opacity];
|
||||
}
|
||||
([sum[0] / n, sum[1] / n, sum[2] / n], sum[3] / n)
|
||||
}
|
||||
_ => ([0.5; 3], 1.0),
|
||||
};
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
[unit(rgb[0]), unit(rgb[1]), unit(rgb[2]), unit(alpha * opacity)]
|
||||
}
|
||||
|
||||
/// Add `mesh` to `out`, counting its triangles into `total`, or an error when that passes `limit`.
|
||||
pub(crate) fn keep_mesh(out: &mut Vec<SolidMesh>, total: &mut usize, mesh: SolidMesh, limit: usize) -> Result<(), String> {
|
||||
*total = total.saturating_add(mesh.mesh.triangles.len());
|
||||
if *total > limit {
|
||||
return Err("The 3D object is too complex to export".into());
|
||||
}
|
||||
out.push(mesh);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The solids effect `fx` builds from `shapes`, as [`art_for`] draws them, as meshes: Rotate turns
|
||||
/// every fill and stroke; Extrude & Bevel and Inflate build one from each shape's top fill and one
|
||||
/// from the outline of each stroke. A stroke whose solid is past the limits is left out.
|
||||
fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize) -> Result<Vec<SolidMesh>, String> {
|
||||
let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…'));
|
||||
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let view = view_options(&p);
|
||||
let mut out = vec![];
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, MAX_MESH_TRIANGLES);
|
||||
if fx.id == ROTATE {
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, _) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?;
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
// Inflate lays out every puff at once (they share one eye); each mesh, and each Extrude &
|
||||
// Bevel solid, is built as it is reached.
|
||||
let mut inflated = (fx.id == INFLATE).then(|| {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view)
|
||||
});
|
||||
let extrude = extrude_options(&p);
|
||||
for (item, member, area, rule) in &parts {
|
||||
let item: &AppearanceItem = item;
|
||||
let mesh = match inflated.as_mut() {
|
||||
Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())),
|
||||
None => vectorcraft_three_d::extrude_mesh(area, *rule, bounds, extrude, view),
|
||||
};
|
||||
match mesh {
|
||||
Ok(mesh) => {
|
||||
let (paint, opacity, _) = paint_of(item, *member);
|
||||
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The solids `n`'s Extrude & Bevel, Inflate, Rotate or Revolve effect builds, as meshes with the
|
||||
/// colors they are painted ([`SolidMesh`]), faces turned away from the viewer included; meshes
|
||||
/// with no triangles are left out. On a group or layer, the effect's solids of its members
|
||||
/// ([`members`]). The object's opacity multiplies every color's. An error when `n` carries no
|
||||
/// such effect, its solids can't be built, or none has a triangle.
|
||||
pub fn three_d_meshes(n: &Node) -> Result<Vec<SolidMesh>, String> {
|
||||
// Triangles of every solid together, against [`MAX_MESH_TRIANGLES`].
|
||||
let mut total = 0usize;
|
||||
let meshes = if crate::has_revolve(n) {
|
||||
let mut out = vec![];
|
||||
for m in crate::revolve::revolve_meshes(n)? {
|
||||
keep_mesh(&mut out, &mut total, m, MAX_MESH_TRIANGLES)?;
|
||||
}
|
||||
out
|
||||
} else if !has_solid(n) {
|
||||
return Err("the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)".into());
|
||||
} else if is_container(n) {
|
||||
let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing to export")?;
|
||||
let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…'));
|
||||
let mut shapes = members(n, label)?;
|
||||
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
|
||||
meshes_for(fx, &shapes, &mut total)?
|
||||
} else {
|
||||
let (path, rule) = profile(n).ok_or("3D export needs a path, compound path, type or group")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let paints = solid_paints(n);
|
||||
if let Some((index, fx)) = solid(&n.appearance.effects) {
|
||||
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
|
||||
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0 }], &mut total)?
|
||||
} else {
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
for item in &paints {
|
||||
if let Some((index, fx)) = solid(item.effects()) {
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }], &mut total)?);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
};
|
||||
let meshes: Vec<SolidMesh> = meshes
|
||||
.into_iter()
|
||||
.filter(|m| !m.mesh.is_empty())
|
||||
.map(|mut m| {
|
||||
m.color[3] *= n.opacity.clamp(0.0, 1.0);
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
if meshes.is_empty() {
|
||||
return Err("its 3D effect builds no solid".into());
|
||||
}
|
||||
Ok(meshes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_mesh;
|
||||
@@ -0,0 +1,140 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_doc::color::{Color, Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_geom::BezPath;
|
||||
|
||||
use super::*;
|
||||
|
||||
const RED: Color = Color::Rgb { r: 0.8, g: 0.2, b: 0.1 };
|
||||
|
||||
fn square_node(id: u64, x: f64) -> Node {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, 100.0));
|
||||
b.line_to((x + 100.0, 100.0));
|
||||
b.line_to((x + 100.0, 200.0));
|
||||
b.line_to((x, 200.0));
|
||||
b.close_path();
|
||||
Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::solid(Color::BLACK), 4.0))
|
||||
}
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
crate::new_effect(id, ¶ms).unwrap()
|
||||
}
|
||||
|
||||
fn close(a: [f32; 4], b: [f32; 4]) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_3d_effect_gives_a_mesh_for_its_fill_and_its_stroke() {
|
||||
for id in SOLIDS {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.effects.push(fx(id, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
assert_eq!(meshes.len(), 2, "{id}: the fill's solid and the stroke's");
|
||||
assert!(close(meshes[0].color, [0.8, 0.2, 0.1, 1.0]), "{id}: {:?}", meshes[0].color);
|
||||
assert!(close(meshes[1].color, [0.0, 0.0, 0.0, 1.0]), "{id}: {:?}", meshes[1].color);
|
||||
assert!(meshes.iter().all(|m| !m.mesh.is_empty()), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_meshes_of_one_object_share_one_triangle_budget() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
let first = meshes[0].mesh.triangles.len();
|
||||
assert!(first > 0);
|
||||
// Every mesh counts against what the ones before it used.
|
||||
let (mut out, mut total) = (vec![], 0);
|
||||
keep_mesh(&mut out, &mut total, meshes[0].clone(), first).unwrap();
|
||||
assert!(keep_mesh(&mut out, &mut total, meshes[1].clone(), first).is_err());
|
||||
assert_eq!(out.len(), 1);
|
||||
// Building past the budget stops with an error instead of holding every mesh.
|
||||
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0 }];
|
||||
let Some(effect) = n.appearance.effects.first() else { panic!("no effect") };
|
||||
let mut total = 0;
|
||||
assert!(meshes_for(effect, &shapes, &mut total).is_ok());
|
||||
let mut total = MAX_MESH_TRIANGLES - first + 1;
|
||||
assert!(meshes_for(effect, &shapes, &mut total).is_err_and(|e| e.contains("too complex")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extruded_mesh_is_as_deep_as_the_effect() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.items.truncate(1);
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({ "depth": 30.0, "rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0 })));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
let (lo, hi) = meshes[0].mesh.bounds().unwrap();
|
||||
assert!((hi[2] - lo[2] - 30.0).abs() < 1e-9 && (hi[0] - lo[0] - 100.0).abs() < 1e-9, "{lo:?} {hi:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_gives_a_mesh_in_the_top_fill() {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((100.0, 40.0));
|
||||
b.line_to((130.0, 60.0));
|
||||
b.line_to((130.0, 140.0));
|
||||
b.line_to((100.0, 160.0));
|
||||
let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
n.appearance.effects.push(fx(crate::REVOLVE, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
assert_eq!(meshes.len(), 1);
|
||||
assert!(close(meshes[0].color, [0.8, 0.2, 0.1, 1.0]));
|
||||
assert!(meshes[0].mesh.triangles.len() >= 64 * 3, "three profile edges swept in 64 steps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_without_a_3d_effect_has_no_mesh() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
assert!(three_d_meshes(&n).is_err());
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
n.appearance.effects[0].visible = false;
|
||||
assert!(three_d_meshes(&n).is_err(), "a hidden effect builds nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_object_and_the_paint_opacities_multiply() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.items.truncate(1);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = 0.5;
|
||||
}
|
||||
n.opacity = 0.5;
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
assert!((meshes[0].color[3] - 0.25).abs() < 1e-6, "{:?}", meshes[0].color);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_on_one_fill_gives_that_fills_mesh_alone() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
|
||||
s.effects.push(fx(EXTRUDE, json!({})));
|
||||
}
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
assert_eq!(meshes.len(), 1);
|
||||
assert!(close(meshes[0].color, [0.0, 0.0, 0.0, 1.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_gives_a_mesh_for_each_member() {
|
||||
let mut g = Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(square_node(2, 300.0))]);
|
||||
g.appearance.effects.push(fx(EXTRUDE, json!({ "rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0 })));
|
||||
let meshes = three_d_meshes(&g).unwrap();
|
||||
assert_eq!(meshes.len(), 4, "each member's fill and stroke");
|
||||
// The members turn about their shared centre: the first is left of it, the second right.
|
||||
let (lo, _) = meshes[0].mesh.bounds().unwrap();
|
||||
let (_, hi) = meshes[2].mesh.bounds().unwrap();
|
||||
assert!(lo[0] < -150.0 && hi[0] > 150.0, "{lo:?} {hi:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_takes_the_average_of_its_stops() {
|
||||
let stops =
|
||||
vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop { opacity: 0.5, ..GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)) }];
|
||||
let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
assert!(close(mesh_color(&paint, 1.0), [0.5, 0.0, 0.5, 0.75]));
|
||||
let pattern = Paint::Pattern { pattern: "x".into(), xf: vectorcraft_geom::Affine::IDENTITY };
|
||||
assert!(close(mesh_color(&pattern, 0.5), [0.5, 0.5, 0.5, 0.5]));
|
||||
}
|
||||
@@ -13,6 +13,8 @@
|
||||
//! fill them ([`gradient_slices`]); Outline Stroke turns the strip into a gradient mesh
|
||||
//! ([`gradient_meshes`]).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use kurbo::{BezPath, Point, Shape, Vec2};
|
||||
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientPaint, Paint};
|
||||
use vectorcraft_doc::live::{H_DOWN, H_LEFT, H_RIGHT, H_UP};
|
||||
@@ -78,14 +80,26 @@ struct Lay<'a> {
|
||||
st: &'a StrokeLayer,
|
||||
/// Half the stroked width ([`aligned_width`]).
|
||||
hw: f64,
|
||||
/// How far ribs reach either side of the path where nothing wider is near.
|
||||
cover: f64,
|
||||
/// How far ribs reach past the stroke's edge.
|
||||
margin: f64,
|
||||
/// How far a strip runs on past the start and end of an open subpath (caps and heads).
|
||||
ext: (f64, f64),
|
||||
}
|
||||
|
||||
impl Lay<'_> {
|
||||
/// How far the stroke reaches either side of the path at fraction `t` of a subpath: its wider
|
||||
/// side, just before or just after a step there.
|
||||
fn half(&self, t: f64) -> f64 {
|
||||
let Some(p) = &self.st.profile else { return self.hw };
|
||||
let ((bl, br), (al, ar)) = p.around(t);
|
||||
self.hw * bl.max(br).max(al).max(ar).max(0.0)
|
||||
}
|
||||
|
||||
/// How far a rib at fraction `t` reaches either side of the path to cover the stroke there.
|
||||
fn cover(&self, t: f64) -> f64 {
|
||||
self.half(t) + self.margin
|
||||
}
|
||||
|
||||
/// The across band at fraction `t` of a subpath whose visible side is `side` (`Some(true)`:
|
||||
/// left; `None`: both, a centred stroke).
|
||||
fn band(&self, t: f64, side: Option<bool>) -> (f64, f64) {
|
||||
@@ -147,10 +161,11 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64,
|
||||
if !(hw > 0.0 && hw.is_finite()) {
|
||||
return vec![];
|
||||
}
|
||||
let full = hw * st.profile_max();
|
||||
let heads = (st.head_reach(false), st.head_reach(true));
|
||||
let cap = cap_extent(st.cap, 2.0 * full);
|
||||
let lay = Lay { st, hw, cover: full + margin, margin, ext: (cap.max(heads.0) + margin, cap.max(heads.1) + margin) };
|
||||
let mut lay = Lay { st, hw, margin, ext: (0.0, 0.0) };
|
||||
// Caps reach as far past the ends as the stroke is wide there.
|
||||
let cap = |t: f64| cap_extent(st.cap, 2.0 * lay.half(t));
|
||||
lay.ext = (cap(0.0).max(heads.0) + margin, cap(1.0).max(heads.1) + margin);
|
||||
let subs = subpaths(bp);
|
||||
let count = subs.len();
|
||||
let mut out = vec![];
|
||||
@@ -165,7 +180,8 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64,
|
||||
// A subpath of no length: a dot (round and projecting caps paint it).
|
||||
1 => {
|
||||
let (d, b, e) = (Vec2::new(1.0, 0.0), lay.band(0.0, side), lay.ext.0.max(lay.ext.1));
|
||||
vec![Rib::square(pts[0] - d * e, d, lay.cover, 0.0, b), Rib::square(pts[0] + d * e, d, lay.cover, 0.0, b)]
|
||||
let r = lay.cover(0.0);
|
||||
vec![Rib::square(pts[0] - d * e, d, r, 0.0, b), Rib::square(pts[0] + d * e, d, r, 0.0, b)]
|
||||
}
|
||||
_ => {
|
||||
let total = length(&pts, closed);
|
||||
@@ -215,9 +231,37 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>,
|
||||
let n = pts.len();
|
||||
let seg_count = if closed { n } else { n - 1 };
|
||||
let dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect();
|
||||
// Ribs near an arrowhead reach across it.
|
||||
let reach = |s: f64| {
|
||||
let mut r = lay.cover;
|
||||
// How far each point is from the next, and along the subpath.
|
||||
let seg: Vec<f64> = (0..n).map(|i| pts[i].distance(pts[(i + 1) % n])).collect();
|
||||
let along: Vec<f64> = seg
|
||||
.iter()
|
||||
.scan(0.0, |s, l| {
|
||||
let at = *s;
|
||||
*s += l;
|
||||
Some(at)
|
||||
})
|
||||
.collect();
|
||||
// How far the ribs at point `i` reach: past the stroke there and on its way to the points
|
||||
// either side, where it is no wider than at one of the two (each side of a width profile
|
||||
// stays between its widths at the points of a span, and its points have points here). The
|
||||
// caps and dots of a dashed stroke reach along the path as far as it is wide where they sit,
|
||||
// so there the ribs cover the widest the stroke gets that far either way. Not as far as the
|
||||
// stroke is wide anywhere: where a stroke crosses or runs close by itself, a narrow part
|
||||
// reaching that far would paint over a wide part beside it (#5960). The start of a closed
|
||||
// subpath is also its end. Ribs near an arrowhead reach across it.
|
||||
let cover: Vec<f64> = (0..n).map(|i| if closed && i == 0 { lay.cover(0.0).max(lay.cover(1.0)) } else { lay.cover(along[i] / total) }).collect();
|
||||
let window = match lay.st.dash {
|
||||
Some(_) if lay.st.profile.is_some() => cap_extent(lay.st.cap, 2.0 * lay.hw * lay.st.profile_max()),
|
||||
_ => 0.0,
|
||||
};
|
||||
let ahead = widest_ahead(&cover, &seg, closed, window);
|
||||
// Behind a point is ahead of it on the subpath run backwards.
|
||||
let back_seg: Vec<f64> = (0..n).map(|i| seg[(2 * n - 2 - i) % n]).collect();
|
||||
let back_cover: Vec<f64> = cover.iter().rev().copied().collect();
|
||||
let behind: Vec<f64> = widest_ahead(&back_cover, &back_seg, closed, window).into_iter().rev().collect();
|
||||
let reach = |i: usize| {
|
||||
let mut r = cover[i].max(ahead[i]).max(behind[i]);
|
||||
let s = along[i];
|
||||
if heads.0 > 0.0 && s <= heads.0 {
|
||||
r = r.max(heads.0 + lay.margin);
|
||||
}
|
||||
@@ -227,29 +271,69 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option<bool>,
|
||||
r
|
||||
};
|
||||
let mut out = Vec::with_capacity(n + 4);
|
||||
let mut s = 0.0;
|
||||
if !closed {
|
||||
let (d, b) = (dir[0], lay.band(0.0, side));
|
||||
out.push(Rib::square(pts[0] - d * lay.ext.0, d, reach(0.0), 0.0, b));
|
||||
out.push(Rib::square(pts[0], d, reach(0.0), 0.0, b));
|
||||
s = pts[0].distance(pts[1]);
|
||||
out.push(Rib::square(pts[0] - d * lay.ext.0, d, reach(0), 0.0, b));
|
||||
out.push(Rib::square(pts[0], d, reach(0), 0.0, b));
|
||||
}
|
||||
let (first, last) = if closed { (0, n) } else { (1, n - 1) };
|
||||
for i in first..last {
|
||||
let v = i % n;
|
||||
let t = s / total;
|
||||
let ribs = lay.turn(pts[v], dir[(v + seg_count - 1) % seg_count], dir[v % seg_count], reach(s), t, lay.band(t, side));
|
||||
let t = along[v] / total;
|
||||
let ribs = lay.turn(pts[v], dir[(v + seg_count - 1) % seg_count], dir[v % seg_count], reach(v), t, lay.band(t, side));
|
||||
// A closed subpath starts after the fan of its first corner and ends with it.
|
||||
let skip = if closed && i == 0 { ribs.len() - 1 } else { 0 };
|
||||
out.extend(ribs.into_iter().skip(skip));
|
||||
s += pts[v].distance(pts[(v + 1) % n]);
|
||||
}
|
||||
if closed {
|
||||
out.extend(lay.turn(pts[0], dir[seg_count - 1], dir[0], reach(total), 1.0, lay.band(1.0, side)));
|
||||
out.extend(lay.turn(pts[0], dir[seg_count - 1], dir[0], reach(0), 1.0, lay.band(1.0, side)));
|
||||
} else {
|
||||
let (d, b) = (dir[seg_count - 1], lay.band(1.0, side));
|
||||
out.push(Rib::square(pts[n - 1], d, reach(total), 1.0, b));
|
||||
out.push(Rib::square(pts[n - 1] + d * lay.ext.1, d, reach(total), 1.0, b));
|
||||
out.push(Rib::square(pts[n - 1], d, reach(n - 1), 1.0, b));
|
||||
out.push(Rib::square(pts[n - 1] + d * lay.ext.1, d, reach(n - 1), 1.0, b));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each of the points of a subpath, how far the ribs of the points ahead of it reach
|
||||
/// (`cover`), out to the first point more than `window` along (or the end of an open subpath,
|
||||
/// or once round a closed one): `seg[i]` is how far point `i` is from the next (past the last,
|
||||
/// the first when `closed`). Both ends of the window only move forward, so a queue of the
|
||||
/// points that reach farther than every point after them gives each maximum, and a subpath
|
||||
/// costs time in proportion to its points however many a window spans.
|
||||
pub(super) fn widest_ahead(cover: &[f64], seg: &[f64], closed: bool, window: f64) -> Vec<f64> {
|
||||
let n = cover.len().min(seg.len());
|
||||
if n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
// A closed subpath's points ahead are numbered on round it once more.
|
||||
let last = if closed { 2 * n - 1 } else { n - 1 };
|
||||
let mut pos = Vec::with_capacity(last + 1);
|
||||
let mut s = 0.0;
|
||||
for k in 0..=last {
|
||||
pos.push(s);
|
||||
s += seg[k % n];
|
||||
}
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut queue: VecDeque<usize> = VecDeque::new();
|
||||
let mut next = 1;
|
||||
for i in 0..n {
|
||||
next = next.max(i + 1);
|
||||
let stop = if closed { i + n } else { last };
|
||||
let mut past = next > i + 1 && pos[next - 1] - pos[i] > window;
|
||||
while !past && next <= stop {
|
||||
let r = cover[next % n];
|
||||
while queue.back().is_some_and(|&k| cover[k % n] <= r) {
|
||||
queue.pop_back();
|
||||
}
|
||||
queue.push_back(next);
|
||||
past = pos[next] - pos[i] > window;
|
||||
next += 1;
|
||||
}
|
||||
while queue.front().is_some_and(|&k| k <= i) {
|
||||
queue.pop_front();
|
||||
}
|
||||
out.push(queue.front().map_or(0.0, |&k| cover[k % n]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -237,3 +237,113 @@ fn slices_cover_an_arrowhead_on_a_long_straight_leg() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the last slice holding `p` (the one filled last there) lay its gradient piece on a part of
|
||||
/// the path running across the page (left or right), for a gradient in `mode`? Along, the piece
|
||||
/// runs the way the path does; across, square to it.
|
||||
fn painted_by_level_part(slices: &[Slice], p: Point, mode: StrokeGradientMode) -> Option<bool> {
|
||||
slices.iter().rev().find(|s| s.shape.contains(p)).map(|s| {
|
||||
let d = s.to - s.from;
|
||||
(d.x.abs() > d.y.abs()) == (mode == StrokeGradientMode::Along)
|
||||
})
|
||||
}
|
||||
|
||||
/// #5960: where a variable-width stroke crosses itself, the later pass paints over the earlier one
|
||||
/// only where the two overlap. Its slices reach as far as the stroke is wide there, not as far as
|
||||
/// it is wide anywhere, so a narrow later pass leaves the wide earlier one its own colour beside it.
|
||||
#[test]
|
||||
fn a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap() {
|
||||
// Right along y = 50, round, then down through the first leg at x = 50, near the narrow end.
|
||||
let crossing = poly(&[(0.0, 50.0), (100.0, 50.0), (100.0, 100.0), (50.0, 100.0), (50.0, 0.0)], false);
|
||||
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
|
||||
let mut st = stroke(10.0, mode);
|
||||
st.profile = Some(WidthProfile::taper_end());
|
||||
let sl = slices(&crossing, &st);
|
||||
// In the first leg (about 4 pt either side of it there) but 4 pt beside the second leg,
|
||||
// which is less than 1 pt either side of itself there.
|
||||
let level = painted_by_level_part(&sl, Point::new(54.0, 52.0), mode);
|
||||
assert_eq!(level, Some(true), "{mode:?}: painted by the second leg");
|
||||
// Where the two overlap, the second leg is on top.
|
||||
let level = painted_by_level_part(&sl, Point::new(50.5, 52.0), mode);
|
||||
assert_eq!(level, Some(false), "{mode:?}: painted by the first leg");
|
||||
assert_covered(&crossing, &st);
|
||||
}
|
||||
}
|
||||
|
||||
/// #5960: a narrow pass running close beside a wide one doesn't paint the wide one's edge.
|
||||
#[test]
|
||||
fn a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone() {
|
||||
// Right along y = 0, then back along y = 7: the way back is the narrow end of a taper.
|
||||
let hairpin = poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 7.0), (0.0, 7.0)], false);
|
||||
let total = 207.0;
|
||||
let mut st = stroke(10.0, StrokeGradientMode::Along);
|
||||
st.profile = Some(WidthProfile::taper_end());
|
||||
let sl = slices(&hairpin, &st);
|
||||
// Half way along the first leg, 3 pt off it (it is about 3.8 pt wide there either side); the
|
||||
// way back is about 1.2 pt wide either side there, so it reaches no nearer than 5.8.
|
||||
let p = Point::new(50.0, 3.0);
|
||||
let t = param(&sl, p).expect("in a slice");
|
||||
assert!((t - 50.0 / total).abs() < 1e-6, "painted with {t}, not the first leg's {}", 50.0 / total);
|
||||
assert_covered(&hairpin, &st);
|
||||
}
|
||||
|
||||
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
|
||||
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
|
||||
/// 256 do.
|
||||
#[test]
|
||||
fn a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone() {
|
||||
// The hairpin above, the way back in 0.01 pt steps: 500 points within a round cap's 5 pt.
|
||||
let mut pts = vec![(0.0, 0.0), (100.0, 0.0)];
|
||||
pts.extend((0..=10_000).map(|i| (100.0 - i as f64 * 0.01, 7.0)));
|
||||
let hairpin = poly(&pts, false);
|
||||
let total = 207.0;
|
||||
let mut st = stroke(10.0, StrokeGradientMode::Along);
|
||||
st.profile = Some(WidthProfile::taper_end());
|
||||
st.cap = LineCap::Round;
|
||||
st.dash = Some(Dash { pattern: vec![12.0, 6.0], ..Default::default() });
|
||||
let sl = slices(&hairpin, &st);
|
||||
let p = Point::new(50.0, 3.0);
|
||||
let t = param(&sl, p).expect("in a slice");
|
||||
assert!((t - 50.0 / total).abs() < 1e-6, "painted with {t}, not the first leg's {}", 50.0 / total);
|
||||
}
|
||||
|
||||
/// The widest the ribs ahead reach is the widest over the points out to the first one more than
|
||||
/// the window along, as a walk along the subpath finds it, open and closed.
|
||||
#[test]
|
||||
fn widest_ahead_is_the_widest_within_the_window() {
|
||||
let mut seed = 0x9e37_79b9_u64;
|
||||
let mut rnd = move || {
|
||||
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||
(seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
};
|
||||
for _ in 0..200 {
|
||||
let n = 1 + (rnd() * 40.0) as usize;
|
||||
let cover: Vec<f64> = (0..n).map(|_| rnd() * 10.0).collect();
|
||||
// Some points on top of each other.
|
||||
let seg: Vec<f64> = (0..n).map(|_| if rnd() < 0.2 { 0.0 } else { rnd() * 3.0 }).collect();
|
||||
let window = [0.0, rnd() * 5.0, rnd() * 200.0][(rnd() * 3.0) as usize];
|
||||
for closed in [false, true] {
|
||||
let got = super::gradient::widest_ahead(&cover, &seg, closed, window);
|
||||
assert_eq!(got.len(), n);
|
||||
for (i, &got) in got.iter().enumerate() {
|
||||
let (mut j, mut d, mut want) = (i, 0.0, 0.0_f64);
|
||||
for _ in 0..n {
|
||||
let k = if closed {
|
||||
(j + 1) % n
|
||||
} else if j + 1 < n {
|
||||
j + 1
|
||||
} else {
|
||||
break;
|
||||
};
|
||||
want = want.max(cover[k]);
|
||||
d += seg[j];
|
||||
j = k;
|
||||
if d > window {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(got, want, "n {n}, closed {closed}, window {window}, point {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,686 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use super::*;
|
||||
use crate::pixel::Channels;
|
||||
use crate::{PixelFx, RasterFx, raster_effects};
|
||||
|
||||
/// A `w` × `h` raster whose pixels are `px` points wide (origin top-left), at a raster effects
|
||||
/// resolution whose pixels are `line` points wide.
|
||||
fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace {
|
||||
let (wd, hd) = (w as f64 * px, h as f64 * px);
|
||||
PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) }
|
||||
}
|
||||
|
||||
/// `w` × `h` premultiplied pixels: `f(x, y)` each.
|
||||
fn image(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {
|
||||
(0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| f(x, y)).collect()
|
||||
}
|
||||
|
||||
fn at(d: &[u8], w: usize, x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * w + x) * 4;
|
||||
[d[i], d[i + 1], d[i + 2], d[i + 3]]
|
||||
}
|
||||
|
||||
/// The effect `svg.filter` with `params`, as the renderer reads it.
|
||||
fn filter(params: serde_json::Value) -> SvgFilterFx {
|
||||
let e = Effect { id: SVG_FILTER.into(), params, visible: true };
|
||||
match raster_effects(&[e]).first() {
|
||||
Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A blue square of `size` pixels inset by `inset` in a transparent raster `w` wide.
|
||||
fn blue_square(w: usize, inset: usize) -> Vec<u8> {
|
||||
image(w, w, |x, y| if (inset..w - inset).contains(&x) && (inset..w - inset).contains(&y) { [0, 0, 255, 255] } else { [0; 4] })
|
||||
}
|
||||
|
||||
const RED_FLOOD: &str = r##"<filter id="Red"><feFlood flood-color="#ff0000"/><feComposite in2="SourceGraphic" operator="in"/></filter>"##;
|
||||
|
||||
#[test]
|
||||
fn check_names_a_filter_by_its_id() {
|
||||
assert_eq!(check(RED_FLOOD), Ok("Red".into()));
|
||||
assert_eq!(check(&format!(" {RED_FLOOD}\n")), Ok("Red".into()), "spaces around the element");
|
||||
let linked = r#"<filter id=" Shadow 1 "><feImage xlink:href="data:image/png;base64,AAAA"/></filter>"#;
|
||||
assert_eq!(check(linked), Ok("Shadow 1".into()), "the xlink prefix is declared for it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_refuses_what_is_not_one_drawable_filter() {
|
||||
for (xml, why) in [
|
||||
("", "give one <filter> element"),
|
||||
("<filter id=\"a\">", "isn't valid XML"),
|
||||
("<g id=\"a\"><feFlood/></g>", "give one <filter> element"),
|
||||
("<filter id=\"a\"><feFlood/></filter><filter id=\"b\"><feFlood/></filter>", "give one <filter> element"),
|
||||
("text<filter id=\"a\"><feFlood/></filter>", "give one <filter> element"),
|
||||
("<filter><feFlood/></filter>", "needs an id"),
|
||||
("<filter id=\" \"><feFlood/></filter>", "needs an id"),
|
||||
("<filter id=\"a\"></filter>", "no primitives"),
|
||||
("<filter id=\"a\"><feTurbulence numOctaves=\"11\"/></filter>", "numOctaves is at most 10"),
|
||||
("<filter id=\"a\"><feConvolveMatrix order=\"3 12\" kernelMatrix=\"1\"/></filter>", "order is at most 9"),
|
||||
("<filter id=\"a\"><feConvolveMatrix order=\"65536+65536\" kernelMatrix=\"1\"/></filter>", "order is at most 9"),
|
||||
("<filter id=\"a\"><feConvolveMatrix order=\"3 x\" kernelMatrix=\"1\"/></filter>", "order is at most 9"),
|
||||
("<filter id=\"a\"><notAPrimitive/></filter>", "<notAPrimitive> isn't an element of an SVG filter"),
|
||||
("<filter id=\"a\"><feOffset/><script>alert(1)</script></filter>", "<script> isn't an element"),
|
||||
("<filter id=\"a\"><feMerge><feMergeNode/><a/></feMerge></filter>", "<a> isn't an element"),
|
||||
("<filter id=\"a\" onload=\"x()\"><feOffset/></filter>", "no event attributes such as onload"),
|
||||
("<filter id=\"a\"><feOffset ONCLICK=\"x()\"/></filter>", "no event attributes such as ONCLICK"),
|
||||
("<filter id=\"a\"><feImage xlink:href=\"javascript:x()\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"photo.png\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"data:image/svg+xml;base64,PHN2Zy8+\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"data:application/gzip;base64,H4sI\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\"><feImage href=\"data:;base64,AAAA\"/></filter>", "WebP data: URLs"),
|
||||
("<filter id=\"a\" width=\"0\"><feOffset/></filter>", "can't be drawn"),
|
||||
] {
|
||||
let e = check(xml).expect_err(xml);
|
||||
assert!(e.contains(why), "{xml}: {e}");
|
||||
}
|
||||
let many = format!("<filter id=\"a\">{}</filter>", "<feOffset/>".repeat(MAX_PRIMITIVES + 1));
|
||||
assert!(check(&many).is_err_and(|e| e.contains("at most 64 primitives")));
|
||||
let titled = format!("<filter id=\"a\"><title>T</title><desc>D</desc>{}</filter>", "<feOffset/>".repeat(MAX_PRIMITIVES));
|
||||
assert_eq!(check(&titled), Ok("a".into()), "a title and a description aren't primitives");
|
||||
assert!(check("<filter id=\"a\"><title>T</title></filter>").is_err_and(|e| e.contains("no primitives")));
|
||||
let long = format!("<filter id=\"{}\"><feOffset/></filter>", "x".repeat(MAX_NAME + 1));
|
||||
assert!(check(&long).is_err_and(|e| e.contains("at most 255 characters")));
|
||||
let big = format!("<filter id=\"a\"><feOffset/><!--{}--></filter>", " ".repeat(SvgFilter::MAX_XML));
|
||||
assert!(check(&big).is_err_and(|e| e.contains("at most 64 KB")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_id_renames_only_the_filter() {
|
||||
let xml = r#"<filter id="Old" x="0"><feOffset result="Old"/></filter>"#;
|
||||
assert_eq!(with_id(xml, "New").as_deref(), Some(r#"<filter id="New" x="0"><feOffset result="Old"/></filter>"#));
|
||||
assert_eq!(with_id("<filter><feOffset/></filter>", "New"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_in_lists_the_documents_filters_it_takes() {
|
||||
let svg = format!(
|
||||
"<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\"><defs>{RED_FLOOD}<filter id=\"Empty\"/><filter id=\"Off\"><feOffset dx=\"2\"/></filter></defs></svg>"
|
||||
);
|
||||
let (found, skipped) = filters_in(&svg);
|
||||
assert_eq!(found.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Red", "Off"]);
|
||||
assert_eq!(found[0].1, RED_FLOOD, "each filter's XML as it is written");
|
||||
assert_eq!(skipped, 1, "the filter without primitives");
|
||||
}
|
||||
|
||||
/// [`filters_of`] on `svg` read as SVG import reads it (with DTDs).
|
||||
fn filters_in(svg: &str) -> (Vec<(String, String)>, usize) {
|
||||
let doc = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).unwrap();
|
||||
filters_of(&doc, svg, usize::MAX, |_| false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_of_stops_at_the_room_left_and_skips_taken_and_styled_filters() {
|
||||
let many = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\">{}</svg>",
|
||||
(0..200).map(|i| format!("<filter id=\"f{i}\"><feOffset/></filter>")).collect::<String>()
|
||||
);
|
||||
let doc = roxmltree::Document::parse(&many).unwrap();
|
||||
let (found, skipped) = filters_of(&doc, &many, 3, |name| name == "f1");
|
||||
assert_eq!(found.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["f0", "f2", "f3"]);
|
||||
assert_eq!(skipped, 197);
|
||||
// A filter whose look comes from the document's styles isn't taken.
|
||||
for styled in [
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.r{flood-color:red}</style><filter id=\"a\"><feFlood class=\"r\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><filter id=\"a\"><feFlood flood-color=\"currentColor\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><filter id=\"a\"><feFlood flood-color=\"CURRENTcolor\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><defs color-interpolation-filters=\"sRGB\"><filter id=\"a\"><feGaussianBlur stdDeviation=\"2\"/></filter></defs></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>@media screen { feFlood { flood-color: red } }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>#a feOffset{dx:2}</style><filter id=\"a\"><feOffset/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.s { content: \"{ /*\" } feFlood { flood-color: red }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.outer { fill: blue; & #a { color: red } }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>@scope (#a) { :scope { color: red } }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>svg { color-interpolation-filters: sRGB }</style><filter id=\"a\"><feGaussianBlur stdDeviation=\"2\"/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>feFlood[data-t=\\;] { flood-color: red }</style><filter id=\"a\"><feFlood/></filter></svg>",
|
||||
] {
|
||||
let doc = roxmltree::Document::parse(styled).unwrap();
|
||||
assert_eq!(filters_of(&doc, styled, usize::MAX, |_| false), (vec![], 1), "{styled}");
|
||||
}
|
||||
// A style sheet for the shapes alone (as CSS export writes), applying the filter to them
|
||||
// included, doesn't reach the filter.
|
||||
for shapes in [
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>.cls-1{fill:#f00}</style><filter id=\"a\"><feOffset/></filter></svg>",
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><style>/* #a */ .shape { filter: url(#a) }</style><filter id=\"a\"><feOffset/></filter></svg>",
|
||||
// An identifier named currentColor takes no color.
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\"><filter id=\"currentColor\"><feOffset result=\"currentColor\"/></filter></svg>",
|
||||
] {
|
||||
let doc = roxmltree::Document::parse(shapes).unwrap();
|
||||
assert_eq!(filters_of(&doc, shapes, usize::MAX, |_| false).0.len(), 1, "{shapes}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_filters_are_refused_before_they_are_parsed() {
|
||||
let deep = format!("<filter id=\"a\"><feMerge>{}<feMergeNode/>{}</feMerge></filter>", "<g>".repeat(20), "</g>".repeat(20));
|
||||
assert!(check(&deep).is_err_and(|e| e.contains("nest at most 16 deep")));
|
||||
assert_eq!(with_id(&deep, "b"), None);
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": deep }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "drawn without it");
|
||||
// Markup in comments, CDATA and attribute values doesn't count.
|
||||
let quoted =
|
||||
format!("<filter id=\"a\" x=\"{}\"><!--{}--><feOffset/><![CDATA[{}]]></filter>", "<g>".repeat(20), "<g>".repeat(20), "<g>".repeat(20));
|
||||
assert_eq!(check("ed), Ok("a".into()));
|
||||
let gt = format!("<filter id=\"a\" title='{}'>{}<feOffset/></filter>", "x>".repeat(20), "<!-- > -->".repeat(3));
|
||||
assert_eq!(check(>), Ok("a".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_replaces_the_pixels_with_its_result() {
|
||||
let w = 20;
|
||||
let mut data = blue_square(w, 5);
|
||||
filter(json!({ "xml": RED_FLOOD })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&data, w, 10, 10), [255, 0, 0, 255], "inside: the flood, cut to the source");
|
||||
assert_eq!(at(&data, w, 1, 1), [0; 4], "outside the source");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_are_in_points_times_scale() {
|
||||
let w = 40;
|
||||
let shift = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dx="4"/></filter>"#;
|
||||
let run = |px: f64, scale: f64| {
|
||||
let n = (w as f64 / px) as usize;
|
||||
let mut data = image(n, n, |x, y| {
|
||||
let (x, y) = (x as f64 * px, y as f64 * px);
|
||||
if (10.0..20.0).contains(&x) && (10.0..20.0).contains(&y) { [0, 0, 255, 255] } else { [0; 4] }
|
||||
});
|
||||
filter(json!({ "xml": shift, "scale": scale })).apply(&mut data, n, n, &space(n, n, px, px));
|
||||
let column = |x: f64| at(&data, n, (x / px) as usize, (15.0 / px) as usize)[3];
|
||||
(column(9.5), column(21.0), column(23.5), column(25.0))
|
||||
};
|
||||
// The square spans 10..20 pt: moved by 4 pt, 14..24.
|
||||
assert_eq!(run(1.0, 1.0), (0, 255, 255, 0));
|
||||
assert_eq!(run(0.5, 1.0), (0, 255, 255, 0), "the same in points at another zoom");
|
||||
// One unit of the filter is half a point: moved by 2 pt, 12..22.
|
||||
assert_eq!(run(1.0, 0.5), (0, 255, 0, 0));
|
||||
}
|
||||
|
||||
/// A user-space region is placed from the effect's origin.
|
||||
#[test]
|
||||
fn user_space_starts_at_the_origin() {
|
||||
let w = 40;
|
||||
// Flood the square, cut to the region x 0..20 of the filter's user space.
|
||||
let half = r##"<filter id="Half" filterUnits="userSpaceOnUse" x="0" y="0" width="20" height="40"><feFlood flood-color="#ff0000"/><feComposite in2="SourceGraphic" operator="in"/></filter>"##;
|
||||
let run = |origin: [f64; 2]| {
|
||||
let mut data = image(w, w, |_, _| [0, 0, 255, 255]);
|
||||
filter(json!({ "xml": half, "origin": origin })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
|
||||
(at(&data, w, 5, 20)[3], at(&data, w, 25, 20)[3])
|
||||
};
|
||||
assert_eq!(run([0.0, 0.0]), (255, 0));
|
||||
assert_eq!(run([20.0, 0.0]), (0, 255), "the region 20 pt to the right");
|
||||
let b = Rect::new(0.0, 0.0, 40.0, 40.0);
|
||||
assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_no_finer_than_the_raster_effects_resolution() {
|
||||
let w = 16;
|
||||
// Columns one view pixel wide, alternately opaque and clear.
|
||||
let stripes = image(w, w, |x, _| if x % 2 == 0 { [0, 0, 255, 255] } else { [0; 4] });
|
||||
let keep = r#"<filter id="Keep" x="0" y="0" width="1" height="1"><feOffset/></filter>"#;
|
||||
let mut fine = stripes.clone();
|
||||
filter(json!({ "xml": keep })).apply(&mut fine, w, w, &space(w, w, 0.25, 0.25));
|
||||
assert_eq!(at(&fine, w, 4, 4)[3], 255);
|
||||
assert_eq!(at(&fine, w, 5, 4)[3], 0, "at the view's resolution the stripes stay");
|
||||
let mut coarse = stripes.clone();
|
||||
filter(json!({ "xml": keep })).apply(&mut coarse, w, w, &space(w, w, 0.25, 1.0));
|
||||
let (a, b) = (at(&coarse, w, 4, 4)[3], at(&coarse, w, 5, 4)[3]);
|
||||
assert!(a < 255 && b > 0, "four view pixels to a raster pixel: the stripes blend ({a}, {b})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draws_nothing_new_without_content_or_a_readable_filter() {
|
||||
let w = 8;
|
||||
let mut empty = vec![0; w * w * 4];
|
||||
filter(json!({ "xml": RED_FLOOD })).apply(&mut empty, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert!(empty.iter().all(|v| *v == 0), "a flood cut to a source that draws nothing");
|
||||
// A filter that doesn't read the source draws on art that draws no pixels: the raster is its box.
|
||||
let mut clear = vec![0; w * w * 4];
|
||||
filter(json!({ "xml": "<filter id=\"G\"><feFlood flood-color=\"#00ff00\"/></filter>" })).apply(&mut clear, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&clear, w, 4, 4), [0, 255, 0, 255]);
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": "<g/>" }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "not a filter: the object is drawn without it");
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": "<filter id=\"x\" width=\"0\"><feOffset/></filter>" }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "a filter resvg can't draw: the object is drawn without it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outset_is_how_far_the_region_reaches() {
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
|
||||
assert!((filter(json!({ "xml": RED_FLOOD })).outset(b) - 10.0).abs() < 1e-9, "the default region: 10% of the width");
|
||||
let wide = r#"<filter id="w" x="-50%" y="0" width="200%" height="100%"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": wide })).outset(b) - 50.0).abs() < 1e-9);
|
||||
let user = r#"<filter id="u" filterUnits="userSpaceOnUse" x="-10" y="0" width="60" height="25"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": user, "scale": 2.0 })).outset(b) - 20.0).abs() < 1e-9, "user units times scale");
|
||||
let inside = r#"<filter id="i" x="0" y="0" width="1" height="1"><feOffset/></filter>"#;
|
||||
assert_eq!(filter(json!({ "xml": inside })).outset(b), 0.0);
|
||||
// User-space lengths in points: -30 pt is -40 user units.
|
||||
let points = r#"<filter id="p" filterUnits="userSpaceOnUse" x="-30pt" y="0" width="100" height="50"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": points })).outset(b) - 40.0).abs() < 1e-9);
|
||||
// In user space, a percentage is a share of the object's box; em, ex and a missing length
|
||||
// take the default region's share of it.
|
||||
let viewport = r#"<filter id="v" filterUnits="userSpaceOnUse" x="-50%" y="0" width="10" height="10"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": viewport })).outset(b) - 50.0).abs() < 1e-9);
|
||||
let far = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1000%" y="0" width="3000%" height="10"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": far })).outset(b) - 1900.0).abs() < 1e-9, "however far it reaches");
|
||||
let font = r#"<filter id="f" filterUnits="userSpaceOnUse" x="-100em" y="0" width="10" height="10"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": font })).outset(b) - 10.0).abs() < 1e-9, "relative to the font");
|
||||
let default = r#"<filter id="d" filterUnits="userSpaceOnUse"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": default })).outset(b) - 10.0).abs() < 1e-9);
|
||||
// In the bounding box, a length with a unit is invalid: the default.
|
||||
let unit = r#"<filter id="u" x="-5mm"><feOffset/></filter>"#;
|
||||
assert!((filter(json!({ "xml": unit })).outset(b) - 10.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_keeps_the_prefixes_an_ancestor_declares() {
|
||||
let svg = r#"<svg:svg xmlns:svg="http://www.w3.org/2000/svg" xmlns:x="urn:other"><svg:defs><svg:filter id="Pre"><svg:feOffset dx="1"/></svg:filter></svg:defs></svg:svg>"#;
|
||||
let (found, skipped) = filters_in(svg);
|
||||
assert_eq!((found.len(), skipped), (1, 0));
|
||||
assert_eq!(
|
||||
found[0].1, r#"<svg:filter xmlns:svg="http://www.w3.org/2000/svg" id="Pre"><svg:feOffset dx="1"/></svg:filter>"#,
|
||||
"only the prefix it uses"
|
||||
);
|
||||
// A declaration on the filter itself, with spaces around its `=`, is kept as it is.
|
||||
let own = r#"<svg xmlns="http://www.w3.org/2000/svg"><defs><s:filter xmlns:s = "http://www.w3.org/2000/svg" id="Own"><s:feOffset/></s:filter></defs></svg>"#;
|
||||
let (found, skipped) = filters_in(own);
|
||||
assert_eq!((found.len(), skipped), (1, 0));
|
||||
assert_eq!(found[0].1, r#"<s:filter xmlns:s = "http://www.w3.org/2000/svg" id="Own"><s:feOffset/></s:filter>"#);
|
||||
// The same declaration again on the filter, and text like one inside an attribute's value.
|
||||
let again = r#"<s:svg xmlns:s="http://www.w3.org/2000/svg"><s:filter xmlns:s="http://www.w3.org/2000/svg" id="A"><s:feOffset/></s:filter><s:filter id="B" color-profile=" xmlns:s = x"><s:feOffset/></s:filter></s:svg>"#;
|
||||
let (found, skipped) = filters_in(again);
|
||||
assert_eq!((found.len(), skipped), (2, 0), "{found:?}");
|
||||
assert!(found[1].1.starts_with(r#"<s:filter xmlns:s="http://www.w3.org/2000/svg" id="B""#), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primitive_forms_tell_filters_with_the_same_primitives_apart() {
|
||||
let a = primitive_forms(r#"<filter id="a"><feOffset dx="1"/></filter>"#).unwrap();
|
||||
let b = primitive_forms(r#"<filter id="b"><feOffset dx="2"/></filter>"#).unwrap();
|
||||
assert_eq!(a.len(), 1);
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(primitive_forms(r#"<filter id="c"><feOffset dx="1"/></filter>"#), Some(a), "the id doesn't count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn costly_parameters_are_capped() {
|
||||
for (xml, why) in [
|
||||
("<filter id=\"a\"><feMorphology radius=\"101\"/></filter>", "radius is at most 100"),
|
||||
("<filter id=\"a\"><feMorphology radius=\"2 1e9\"/></filter>", "radius is at most 100"),
|
||||
("<filter id=\"a\"><feMorphology radius=\"50+500\"/></filter>", "radius is at most 100"),
|
||||
("<filter id=\"a\"><feGaussianBlur stdDeviation=\"501\"/></filter>", "stdDeviation is at most 500"),
|
||||
("<filter id=\"a\"><feDropShadow stdDeviation=\"1 9e9\"/></filter>", "stdDeviation is at most 500"),
|
||||
(
|
||||
"<filter id=\"a\"><feDiffuseLighting kernelUnitLength=\"101\"><feDistantLight/></feDiffuseLighting></filter>",
|
||||
"kernelUnitLength is at most 100",
|
||||
),
|
||||
] {
|
||||
let e = check(xml).expect_err(xml);
|
||||
assert!(e.contains(why), "{xml}: {e}");
|
||||
}
|
||||
assert_eq!(check("<filter id=\"a\"><feMorphology radius=\"100\"/></filter>"), Ok("a".into()));
|
||||
// usvg also reads attributes in the SVG, XLink and XML namespaces by their local names.
|
||||
for prefixed in [
|
||||
"<filter id=\"a\" xmlns:s=\"http://www.w3.org/2000/svg\"><feMorphology s:radius=\"1000\"/></filter>",
|
||||
"<filter id=\"a\" xmlns:s=\"http://www.w3.org/2000/svg\"><feGaussianBlur s:stdDeviation=\"1e6\"/></filter>",
|
||||
] {
|
||||
assert!(check(prefixed).is_err(), "{prefixed}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter is drawn and written rebuilt from its filter elements and their filter attributes:
|
||||
/// no comments, text, descriptions, other attributes or prefixes.
|
||||
#[test]
|
||||
fn the_filter_is_drawn_and_written_from_its_filter_parts_alone() {
|
||||
let xml = concat!(
|
||||
"<filter id=\"a\" xmlns:s=\"http://www.w3.org/2000/svg\" data-x=\"1\"><!-- note --><desc><script></desc><title>T</title>",
|
||||
"<feFlood flood-color=\"blue\" style=\"flood-color: red; fill: url(#x); flood-opacity: url(#y)\" foo=\""\"/>",
|
||||
"<feMorphology s:radius=\"2\"/><feImage xlink:href=\"data:image/png;base64,AAAA\"/></filter>",
|
||||
);
|
||||
let f = filter(json!({ "xml": xml }));
|
||||
assert_eq!(
|
||||
f.xml(),
|
||||
"<filter id=\"a\"><feFlood flood-color=\"red\"/><feMorphology radius=\"2\"/><feImage href=\"data:image/png;base64,AAAA\"/></filter>"
|
||||
);
|
||||
// An image keeps how it is scaled, as a style declaration.
|
||||
for image in [
|
||||
"<filter id=\"i\"><feImage image-rendering=\"pixelated\" href=\"data:image/png;base64,AAAA\"/></filter>",
|
||||
"<filter id=\"i\"><feImage style=\"image-rendering: pixelated; fill: red\" href=\"data:image/png;base64,AAAA\"/></filter>",
|
||||
] {
|
||||
assert_eq!(
|
||||
filter(json!({ "xml": image })).xml(),
|
||||
"<filter id=\"i\"><feImage href=\"data:image/png;base64,AAAA\" style=\"image-rendering:pixelated\"/></filter>",
|
||||
"{image}"
|
||||
);
|
||||
}
|
||||
// `currentColor` keeps the color it names.
|
||||
let colored = filter(json!({ "xml": "<filter id=\"c\" color=\"red\"><feFlood flood-color=\"currentColor\" style=\"color: blue\"/></filter>" }));
|
||||
assert_eq!(colored.xml(), "<filter id=\"c\" color=\"red\"><feFlood flood-color=\"currentColor\" color=\"blue\"/></filter>");
|
||||
}
|
||||
|
||||
/// An image of a filter is a PNG, JPEG, GIF or WebP, by its bytes, within the pixel cap by its header.
|
||||
#[test]
|
||||
fn filter_images_are_small_raster_images() {
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
image::ImageEncoder::write_image(
|
||||
image::codecs::png::PngEncoder::new(&mut out),
|
||||
&vec![0; (w * h * 4) as usize],
|
||||
w,
|
||||
h,
|
||||
image::ExtendedColorType::Rgba8,
|
||||
)
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
let raster_image = |data| raster_image_sized(data).map(|(kind, _)| kind);
|
||||
assert!(matches!(raster_image(Arc::new(png(2, 2))), Some(usvg::ImageKind::PNG(_))));
|
||||
assert_eq!(raster_image_sized(Arc::new(png(3, 2))).map(|(_, n)| n), Some(6), "its pixel count");
|
||||
// A header that claims more pixels than the cap: the IHDR's width, with its CRC fixed.
|
||||
let mut big = png(2, 2);
|
||||
big[16..20].copy_from_slice(&5000u32.to_be_bytes());
|
||||
big[20..24].copy_from_slice(&5000u32.to_be_bytes());
|
||||
let crc = crc32(&big[12..29]);
|
||||
big[29..33].copy_from_slice(&crc.to_be_bytes());
|
||||
assert!(raster_image(Arc::new(big)).is_none(), "past the pixel cap");
|
||||
assert!(raster_image(Arc::new(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>".to_vec())).is_none(), "SVG");
|
||||
assert!(raster_image(Arc::new(vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0])).is_none(), "compressed SVG");
|
||||
}
|
||||
|
||||
/// A 2 × 2 PNG whose header claims `w` × `h` pixels (its IHDR rewritten, with the CRC fixed).
|
||||
fn png_claiming(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &[0; 16], 2, 2, image::ExtendedColorType::Rgba8).unwrap();
|
||||
out[16..20].copy_from_slice(&w.to_be_bytes());
|
||||
out[20..24].copy_from_slice(&h.to_be_bytes());
|
||||
let crc = crc32(&out[12..29]);
|
||||
out[29..33].copy_from_slice(&crc.to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A filter's images share the pixel cap: images that are each within it but pass it together
|
||||
/// are refused.
|
||||
#[test]
|
||||
fn a_filters_images_share_the_pixel_cap() {
|
||||
let img = |w: u32, h: u32| format!("<feImage href=\"data:image/png;base64,{}\"/>", base64(&png_claiming(w, h)));
|
||||
let half = img(4096, 2048);
|
||||
let err = check(&format!("<filter id=\"a\">{half}{}</filter>", img(4096, 2049))).unwrap_err();
|
||||
assert!(err.contains("pixels in all"), "{err}");
|
||||
let err = check(&format!("<filter id=\"a\">{half}{half}{}</filter>", img(1, 1))).unwrap_err();
|
||||
assert!(err.contains("pixels in all"), "{err}");
|
||||
assert!(check(&format!("<filter id=\"a\">{half}{half}</filter>")).is_ok(), "two halves fill the cap exactly");
|
||||
}
|
||||
|
||||
/// The image limit is for a filter's own images: the object it runs on is its source graphic
|
||||
/// whatever its size.
|
||||
#[test]
|
||||
fn a_large_object_is_still_the_source_graphic() {
|
||||
let w = 4097;
|
||||
let mut d = blue_square(w, 0);
|
||||
filter(json!({ "xml": RED_FLOOD })).apply(&mut d, w, w, &space(w, w, 1.0, 1.0));
|
||||
assert_eq!(at(&d, w, w / 2, w / 2), [255, 0, 0, 255]);
|
||||
}
|
||||
|
||||
fn crc32(bytes: &[u8]) -> u32 {
|
||||
let mut c = !0u32;
|
||||
for b in bytes {
|
||||
c ^= u32::from(*b);
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
/// A user-space region in percentages is written in user units, measured against the object's box.
|
||||
#[test]
|
||||
fn a_region_measured_against_the_box_is_written_out() {
|
||||
let far = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-50%" y="0" width="200%" height="10"><feOffset/></filter>"#;
|
||||
let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] }));
|
||||
assert_eq!(
|
||||
f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(),
|
||||
Some(r#"<filter id="r" filterUnits="userSpaceOnUse" x="-10" y="0" width="40" height="10"><feOffset/></filter>"#)
|
||||
);
|
||||
let plain = filter(json!({ "xml": RED_FLOOD }));
|
||||
assert_eq!(plain.written_xml(Rect::new(0.0, 0.0, 1.0, 1.0)).as_deref(), Some(plain.xml()));
|
||||
}
|
||||
|
||||
/// A filter at the size limit whose region is measured against the box still draws: written in
|
||||
/// user units, the region can make the drawn form longer than the limit.
|
||||
#[test]
|
||||
fn a_filter_at_the_size_limit_draws_with_its_measured_region() {
|
||||
let open = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1%" y="-1%" width="1%" height="1%"><feOffset result=""#;
|
||||
let close = r#""/><feOffset/></filter>"#;
|
||||
let xml = format!("{open}{}{close}", "a".repeat(SvgFilter::MAX_XML - open.len() - close.len()));
|
||||
assert_eq!(xml.len(), SvgFilter::MAX_XML);
|
||||
assert_eq!(check(&xml), Ok("r".into()));
|
||||
let f = filter(json!({ "xml": xml }));
|
||||
let written = f.written_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap();
|
||||
assert!(written.len() > SvgFilter::MAX_XML, "the region written out is longer: {} bytes", written.len());
|
||||
assert!(with_id(&written, DRAWN_ID).is_some(), "the drawn form is read");
|
||||
}
|
||||
|
||||
/// Only a type selector naming a filter or one of its elements, or `*`, lets a style sheet reach
|
||||
/// filters: class, id, attribute and pseudo-class names that contain "filter" or "fe" don't.
|
||||
#[test]
|
||||
fn style_sheets_reach_filters_only_through_their_type_selectors() {
|
||||
let reaches = |sheet: &str| {
|
||||
let svg = format!("<svg xmlns=\"http://www.w3.org/2000/svg\"><style>{sheet}</style></svg>");
|
||||
Styles::of(&roxmltree::Document::parse(&svg).unwrap()).reach_filters
|
||||
};
|
||||
for sheet in
|
||||
[".filter-button { color: red }", "#feature, .fe-icon { fill: blue }", "[data-filter] { fill: red }", "a:hover, rect.filter { stroke: red }"]
|
||||
{
|
||||
assert!(!reaches(sheet), "{sheet}");
|
||||
}
|
||||
for sheet in
|
||||
["filter { x: 0 }", "FeFlood { flood-color: red }", "svg|feBlend { mode: multiply }", "* { color: red }", "g :is(feGaussianBlur) { x: 0 }"]
|
||||
{
|
||||
assert!(reaches(sheet), "{sheet}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute selector styles a filter whose elements carry that attribute, whatever its value
|
||||
/// or namespace prefix; a filter without it is not affected.
|
||||
#[test]
|
||||
fn an_attribute_selector_styles_a_filter_with_that_attribute() {
|
||||
let depends = |sheet: &str, filter: &str| {
|
||||
let svg = format!("<svg xmlns=\"http://www.w3.org/2000/svg\"><style>{sheet}</style><defs>{filter}</defs></svg>");
|
||||
let doc = roxmltree::Document::parse(&svg).unwrap();
|
||||
let f = doc.descendants().find(|n| n.tag_name().name() == "filter").unwrap();
|
||||
depends_on_styles(f, &Styles::of(&doc))
|
||||
};
|
||||
let tagged = r#"<filter id="a"><feFlood data-tone="warm"/></filter>"#;
|
||||
let plain = r#"<filter id="a"><feFlood/></filter>"#;
|
||||
for sheet in ["[data-tone] { flood-color: red }", "[data-tone=\"warm\"] { flood-color: red }", "[svg|data-tone ~= warm] { x: 0 }"] {
|
||||
assert!(depends(sheet, tagged), "{sheet}");
|
||||
assert!(!depends(sheet, plain), "{sheet}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_of_reads_at_most_256_filters() {
|
||||
let many = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\">{}</svg>",
|
||||
(0..300).map(|i| format!("<filter id=\"f{i}\"><feOffset/></filter>")).collect::<String>()
|
||||
);
|
||||
let doc = roxmltree::Document::parse(&many).unwrap();
|
||||
let (found, skipped) = filters_of(&doc, &many, usize::MAX, |_| false);
|
||||
assert_eq!((found.len(), skipped), (MAX_FILTERS_READ, 300 - MAX_FILTERS_READ));
|
||||
}
|
||||
|
||||
/// However large `scale` makes them, a morphology radius spans at most 32 pixels of the raster the
|
||||
/// filter runs on, and a standard deviation at most 512.
|
||||
#[test]
|
||||
fn costly_lengths_are_clamped_in_pixels() {
|
||||
let sp = space(10, 10, 0.5, 0.5);
|
||||
let morph = filter(json!({ "xml": "<filter id=\"m\"><feMorphology radius=\"100\"/></filter>", "scale": 1000.0 }));
|
||||
let s = morph.resolution(&sp, 10.0);
|
||||
assert!(100.0 * 1000.0 / 0.5 * s <= 32.0 + 1e-6, "{s}");
|
||||
let blur = filter(json!({ "xml": "<filter id=\"b\"><feGaussianBlur stdDeviation=\"500\"/></filter>", "scale": 1000.0 }));
|
||||
let s = blur.resolution(&sp, 10.0);
|
||||
assert!(500.0 * 1000.0 / 0.5 * s <= 512.0 + 1e-6, "{s}");
|
||||
// At a fine raster too (1200 ppi): the cap holds.
|
||||
let fine = space(10, 10, 0.06, 0.06);
|
||||
let s = morph.resolution(&fine, 10.0);
|
||||
assert!(100.0 * 1000.0 / 0.06 * s <= 32.0 + 1e-6, "{s}");
|
||||
let small = filter(json!({ "xml": "<filter id=\"s\"><feMorphology radius=\"1\"/></filter>" }));
|
||||
assert_eq!(small.resolution(&sp, 10.0), 1.0, "a small radius runs at the raster's own pixels");
|
||||
// In the object's bounding box, a radius is a fraction of its box: half a 4096-pixel box.
|
||||
let boxed = filter(json!({ "xml": "<filter id=\"o\" primitiveUnits=\"objectBoundingBox\"><feMorphology radius=\"0.5\"/></filter>" }));
|
||||
let s = boxed.resolution(&sp, 4096.0);
|
||||
assert!(0.5 * 4096.0 * s <= 32.0 + 1e-6, "{s}");
|
||||
}
|
||||
|
||||
/// A filter that `check` refuses is never drawn, whatever path put it in an effect.
|
||||
#[test]
|
||||
fn an_unchecked_filter_is_not_drawn() {
|
||||
for xml in [
|
||||
"<filter id=\"a\"><feOffset/><script>alert(1)</script></filter>",
|
||||
"<filter id=\"a\"><feMorphology radius=\"1e6\"/></filter>",
|
||||
"<filter id=\"a\" onload=\"x()\"><feOffset/></filter>",
|
||||
] {
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": xml }), visible: true };
|
||||
assert!(raster_effects(&[e]).is_empty(), "{xml}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Scale Strokes & Effects scales the filter's lengths with the art: the points a unit measures.
|
||||
#[test]
|
||||
fn scaling_the_effect_scales_its_units() {
|
||||
let mut e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": RED_FLOOD }), visible: true };
|
||||
crate::scale_effect(&mut e, 2.0);
|
||||
assert_eq!(e.params["scale"], json!(2.0));
|
||||
crate::scale_effect(&mut e, 0.25);
|
||||
assert_eq!(e.params["scale"], json!(0.5));
|
||||
}
|
||||
|
||||
/// The form SVG output writes, for a filter that fills a 10 × 10 point box.
|
||||
fn written(xml: &str) -> Option<String> {
|
||||
filter(json!({ "xml": xml })).written_xml(Rect::new(0.0, 0.0, 10.0, 10.0))
|
||||
}
|
||||
|
||||
/// SVG 1.1 output writes an image's reference as `xlink:href`; the filter as it is drawn and
|
||||
/// listed keeps `href`.
|
||||
#[test]
|
||||
fn an_image_is_written_with_an_xlink_reference() {
|
||||
let data = format!("data:image/png;base64,{}", base64(&png_claiming(2, 2)));
|
||||
let f = filter(json!({ "xml": format!(r#"<filter id="i"><feImage href="{data}"/></filter>"#) }));
|
||||
assert_eq!(f.xml(), format!(r#"<filter id="i"><feImage href="{data}"/></filter>"#));
|
||||
let out = f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).unwrap();
|
||||
assert_eq!(out, format!(r#"<filter id="i"><feImage xlink:href="{data}"/></filter>"#));
|
||||
assert!(f.writes_as_svg11());
|
||||
assert_eq!(check(&out), Ok("i".into()), "the written form reads back");
|
||||
}
|
||||
|
||||
/// SVG 1.1 has no `feDropShadow`: it is written as the primitives Filter Effects gives as its
|
||||
/// equivalent, with its defaults, input, result and subregion, and results no other primitive uses.
|
||||
#[test]
|
||||
fn a_drop_shadow_is_written_as_svg_1_1_primitives() {
|
||||
assert_eq!(
|
||||
written(r#"<filter id="s"><feDropShadow/></filter>"#).as_deref(),
|
||||
Some(concat!(
|
||||
r#"<filter id="s"><feGaussianBlur in="SourceGraphic" stdDeviation="2"/><feOffset dx="2" dy="2" result="vcShadow0"/><feFlood/>"#,
|
||||
r#"<feComposite in2="vcShadow0" operator="in" result="vcShadow1"/><feMerge><feMergeNode in="vcShadow1"/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
))
|
||||
);
|
||||
// Its input, result, subregion, color space and flood; a name the filter uses is not taken.
|
||||
let given = r#"<filter id="s"><feOffset dx="1" result="vcShadow0"/><feDropShadow in="vcShadow0" result="r" x="1" width="5" dx="3" dy="-1" stdDeviation="1 2" flood-color="rgba(255,0,0,0.5)" flood-opacity="50%" color-interpolation-filters="sRGB"/></filter>"#;
|
||||
assert_eq!(
|
||||
written(given).as_deref(),
|
||||
Some(concat!(
|
||||
r#"<filter id="s"><feOffset dx="1" result="vcShadow0"/>"#,
|
||||
r#"<feGaussianBlur in="vcShadow0" stdDeviation="1 2" color-interpolation-filters="sRGB"/><feOffset dx="3" dy="-1" result="vcShadow1" color-interpolation-filters="sRGB"/>"#,
|
||||
r##"<feFlood flood-color="#ff0000" flood-opacity="0.25098" color-interpolation-filters="sRGB"/>"##,
|
||||
r#"<feComposite in2="vcShadow1" operator="in" result="vcShadow2" color-interpolation-filters="sRGB"/>"#,
|
||||
r#"<feMerge x="1" width="5" result="r" color-interpolation-filters="sRGB"><feMergeNode in="vcShadow2"/><feMergeNode in="vcShadow0"/></feMerge></filter>"#,
|
||||
))
|
||||
);
|
||||
// An implicit input, or a result no earlier primitive has, is the previous result, named.
|
||||
for shadow in [r#"<feDropShadow dx="1"/>"#, r#"<feDropShadow in="nowhere" dx="1"/>"#] {
|
||||
let out = written(&format!(r#"<filter id="s"><feFlood flood-color="blue"/>{shadow}</filter>"#)).unwrap();
|
||||
assert!(out.starts_with(r##"<filter id="s"><feFlood flood-color="#0000ff" result="vcShadow0"/><feGaussianBlur in="vcShadow0""##), "{out}");
|
||||
assert!(out.ends_with(r#"<feMergeNode in="vcShadow0"/></feMerge></filter>"#), "{out}");
|
||||
assert_eq!(check(&out), Ok("s".into()), "the written form reads back");
|
||||
}
|
||||
// What SVG 1.1 can't hold leaves the filter to be written as other pixel effects are.
|
||||
for xml in [
|
||||
r#"<filter id="s"><feDropShadow flood-color="currentColor"/></filter>"#,
|
||||
r#"<filter id="s" primitiveUnits="objectBoundingBox"><feDropShadow/></filter>"#,
|
||||
] {
|
||||
let f = filter(json!({ "xml": xml }));
|
||||
assert!(!f.writes_as_svg11() && f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).is_none(), "{xml}");
|
||||
}
|
||||
// An offset that isn't a number is the shadow's default, which an `feOffset` doesn't share.
|
||||
let out = written(r#"<filter id="s"><feDropShadow dx="bad" dy="-3"/></filter>"#).unwrap();
|
||||
assert!(out.contains(r#"<feOffset dx="2" dy="-3""#), "{out}");
|
||||
// Expanded shadows past the primitive cap.
|
||||
let many = format!(r#"<filter id="s">{}</filter>"#, "<feDropShadow/>".repeat(13));
|
||||
assert!(!filter(json!({ "xml": many })).writes_as_svg11());
|
||||
}
|
||||
|
||||
/// Each input is written as the primitive it reads when drawn: a result name only usvg gives (to
|
||||
/// a primitive without a `result`, here the shadow), and the inputs usvg draws as `SourceGraphic`.
|
||||
#[test]
|
||||
fn inputs_are_written_as_the_primitives_they_read() {
|
||||
let xml = r#"<filter id="s"><feOffset dx="1"/><feDropShadow in="BackgroundImage"/><feOffset dx="2"/><feMerge><feMergeNode in="result2"/><feMergeNode in="FillPaint"/></feMerge><feComposite in="result1" in2="StrokePaint"/></filter>"#;
|
||||
let out = written(xml).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
concat!(
|
||||
r#"<filter id="s"><feOffset dx="1" result="vcShadow1"/>"#,
|
||||
r#"<feGaussianBlur in="SourceGraphic" stdDeviation="2"/><feOffset dx="2" dy="2" result="vcShadow2"/><feFlood/>"#,
|
||||
r#"<feComposite in2="vcShadow2" operator="in" result="vcShadow3"/><feMerge result="vcShadow0"><feMergeNode in="vcShadow3"/><feMergeNode in="SourceGraphic"/></feMerge>"#,
|
||||
r#"<feOffset dx="2"/><feMerge><feMergeNode in="vcShadow0"/><feMergeNode in="SourceGraphic"/></feMerge>"#,
|
||||
r#"<feComposite in="vcShadow1" in2="SourceGraphic"/></filter>"#,
|
||||
)
|
||||
);
|
||||
assert_eq!(check(&out), Ok("s".into()), "the written form reads back");
|
||||
}
|
||||
|
||||
/// Other values SVG 1.1 lacks: SVG 1.1 values that draw alike, or no SVG 1.1 form.
|
||||
#[test]
|
||||
fn values_svg_1_1_lacks_are_written_as_resvg_draws_them() {
|
||||
// `lighter` (Filter Effects) is drawn as the default `over`, and a blur has no `edgeMode`.
|
||||
assert_eq!(
|
||||
written(r#"<filter id="c"><feComposite in2="SourceAlpha" operator="lighter"/><feGaussianBlur stdDeviation="1" edgeMode="wrap"/></filter>"#)
|
||||
.as_deref(),
|
||||
Some(r#"<filter id="c"><feComposite in2="SourceAlpha"/><feGaussianBlur stdDeviation="1"/></filter>"#)
|
||||
);
|
||||
assert_eq!(
|
||||
written(r#"<filter id="c"><feBlend in2="SourceAlpha" mode="multiply"/></filter>"#).as_deref(),
|
||||
Some(r#"<filter id="c"><feBlend in2="SourceAlpha" mode="multiply"/></filter>"#)
|
||||
);
|
||||
// CSS colors as `#rrggbb`, a flood color's alpha in its opacity, a lighting color's dropped.
|
||||
assert_eq!(
|
||||
written(r#"<filter id="c" color="hsl(120, 100%, 50%)"><feFlood flood-color="transparent"/><feDiffuseLighting lighting-color="rgba(0,0,255,0.5)"><feDistantLight/></feDiffuseLighting></filter>"#)
|
||||
.as_deref(),
|
||||
Some(
|
||||
r##"<filter id="c" color="#00ff00"><feFlood flood-color="#000000" flood-opacity="0"/><feDiffuseLighting lighting-color="#0000ff"><feDistantLight/></feDiffuseLighting></filter>"##
|
||||
)
|
||||
);
|
||||
// Image scaling as an SVG 1.1 keyword.
|
||||
let data = format!("data:image/png;base64,{}", base64(&png_claiming(2, 2)));
|
||||
for (given, kept) in
|
||||
[("pixelated", "optimizeSpeed"), ("crisp-edges", "optimizeSpeed"), ("smooth", "optimizeQuality"), ("auto", "optimizeQuality")]
|
||||
{
|
||||
let out = written(&format!(r#"<filter id="i"><feImage style="image-rendering:{given}" href="{data}"/></filter>"#)).unwrap();
|
||||
assert!(out.contains(&format!(r#"style="image-rendering:{kept}""#)), "{given}: {out}");
|
||||
}
|
||||
// The blend modes SVG 1.1 lacks have no SVG 1.1 form.
|
||||
for mode in LATER_BLEND_MODES {
|
||||
let f = filter(json!({ "xml": format!(r#"<filter id="b"><feBlend in2="SourceAlpha" mode="{mode}"/></filter>"#) }));
|
||||
assert!(!f.writes_as_svg11(), "{mode}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_pads_as_rfc_4648_does() {
|
||||
assert_eq!(base64(b""), "");
|
||||
assert_eq!(base64(b"f"), "Zg==");
|
||||
assert_eq!(base64(b"fo"), "Zm8=");
|
||||
assert_eq!(base64(b"foo"), "Zm9v");
|
||||
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Live evaluation without an engine session makes envelopes measure type by its glyph outlines.
|
||||
//! One test in its own process, so nothing else has registered the measure before the evaluation.
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
/// The largest distance between the edges of `a` and `b`.
|
||||
fn off(a: Rect, b: Rect) -> f64 {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() {
|
||||
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
|
||||
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
|
||||
let laid = n.geometric_bounds().unwrap();
|
||||
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
|
||||
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
|
||||
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
|
||||
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
|
||||
|
||||
let _ = vectorcraft_effects::expand_live(None, &n);
|
||||
let after = vectorcraft_doc::live::envelope_content_bounds(&[n]).unwrap();
|
||||
assert!(off(after, ink) < 1e-6, "after live evaluation, type is measured by its glyphs: {after:?} vs {ink:?}");
|
||||
}
|
||||
@@ -9,10 +9,14 @@ description = "VectorCraft engine: sessions, history, selection, the command reg
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = ["bundled-fonts"]
|
||||
default = ["bundled-fonts", "heif"]
|
||||
# The fonts vectorcraft-text bundles (see its `bundled-fonts`). Embedders that supply every font at
|
||||
# run time (`vectorcraft_text::FontDb::add_font`) build with `default-features = false`.
|
||||
bundled-fonts = ["vectorcraft-text/bundled-fonts"]
|
||||
# HEIC and HEIF images open and place, decoded by heic-rs (an HEVC decoder). A build without this
|
||||
# feature still recognizes the files and refuses them with a message. The apps list it beside
|
||||
# `bundled-fonts`.
|
||||
heif = ["dep:heic-rs", "dep:rayon"]
|
||||
|
||||
[dependencies]
|
||||
# Which paths stored in documents may be opened.
|
||||
@@ -37,6 +41,8 @@ vectorcraft-affinity = { workspace = true }
|
||||
vectorcraft-scriptcheck = { workspace = true }
|
||||
image = { workspace = true }
|
||||
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
|
||||
# Pure Rust, no unsafe; pinned at the version photocraft-heif uses.
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], optional = true }
|
||||
flate2 = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# The XML parts of Word documents placed as type (place/docx.rs).
|
||||
@@ -54,6 +60,11 @@ log = { workspace = true }
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "process"] }
|
||||
|
||||
# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
|
||||
rayon = { version = "1.12", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
vectorcraft-affinity = { workspace = true, features = ["synth"] }
|
||||
crc32fast = { workspace = true }
|
||||
@@ -66,3 +77,5 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
|
||||
vectorcraft-js = { workspace = true }
|
||||
+33
-14
@@ -1,5 +1,6 @@
|
||||
//! The command registry. Ids follow Illustrator's menu structure.
|
||||
|
||||
pub mod actionset;
|
||||
mod addons;
|
||||
pub(crate) mod appearance;
|
||||
mod assets;
|
||||
@@ -83,6 +84,7 @@ pub(crate) mod slices;
|
||||
mod stroke;
|
||||
mod style;
|
||||
pub mod stylelib;
|
||||
mod svgfilter;
|
||||
mod swatch;
|
||||
pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
@@ -317,6 +319,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
v.extend(newart::specs());
|
||||
v.extend(colortheme::specs());
|
||||
v.extend(fileio::pdf::specs());
|
||||
@@ -344,6 +347,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(halftone::specs());
|
||||
v.extend(perspgrid::specs());
|
||||
v.extend(shortcutset::specs());
|
||||
v.extend(actionset::specs());
|
||||
v.extend(importmatches::specs());
|
||||
v.extend(addons::specs());
|
||||
v
|
||||
@@ -575,21 +579,31 @@ pub(crate) fn named_id(p: &Value) -> Result<Option<NodeId>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Objects a command targets: explicit `ids` param or the selection.
|
||||
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
// Objects given are used as given: a value that isn't an object id fails rather than the
|
||||
// command acting on the selection instead (#785).
|
||||
match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) => return a.iter().map(object_id).collect(),
|
||||
Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))),
|
||||
None => {}
|
||||
/// The object `p` gives as `key`, for a command that acts on the selection (or makes something new)
|
||||
/// without it: `None` when `p` leaves it out or gives null. Any other value that isn't an object id
|
||||
/// (`"abc"`, `"5"`, `true`, `{}`, `-1`, `2.5`) is an error under `cmd` that names `key`, never the
|
||||
/// selection. The id is not looked up in the document.
|
||||
pub(crate) fn object_param(p: &Value, key: &str, cmd: &str) -> Result<Option<NodeId>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(r)) if key == "id" && r.starts_with('$') => {
|
||||
Err(bad(cmd, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(v) => v.as_u64().map(|id| Some(NodeId(id))).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number"))),
|
||||
}
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
Some(v @ Value::Number(_)) => Ok(vec![object_id(v)?]),
|
||||
// A step reference a batch couldn't resolve (other strings are other ids, such as an
|
||||
// effect's).
|
||||
Some(Value::String(r)) if r.starts_with('$') => Err(unresolved_reference(r)),
|
||||
_ => Ok(s.doc()?.selection.objects.clone()),
|
||||
}
|
||||
|
||||
/// Objects a command targets: its `ids`, else its `id` as `ids` of one ([`named_ids`]), else the
|
||||
/// selection. An `ids` or `id` that isn't an object id is an error, never the selection. The
|
||||
/// selection is refused while an object of a dynamic symbol instance's art is selected, as by
|
||||
/// [`edit::selected_roots`].
|
||||
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match named_ids(p)? {
|
||||
Some(ids) => Ok(ids),
|
||||
None => {
|
||||
edit::refuse_symbol_part(s)?;
|
||||
Ok(s.doc()?.selection.objects.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -662,6 +676,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
@@ -722,6 +737,10 @@ pub use pathops::shape_count;
|
||||
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
|
||||
pub use buildcmds::live_paint_gaps;
|
||||
|
||||
/// Whether Reset Transformation changes a symbol instance (the Symbols panel menu and the
|
||||
/// Control bar enable it when it changes one).
|
||||
pub use brushsym::reset_transformation_changes;
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
//! Action sets another app saves as text (`.aia` files that start `/version`), read into their
|
||||
//! actions and steps without changing anything (`actionSet.read`).
|
||||
//!
|
||||
//! The text is a set of fields and blocks. A slash name followed by a value sets a field, and a
|
||||
//! slash name followed by `{` opens a block that `}` closes. A value is a decimal number, text in
|
||||
//! parentheses, a byte count and hexadecimal bytes in square brackets (`[ 5 48656c6c6f ]`, UTF-8
|
||||
//! text, which can run over several words), or a byte count and hexadecimal bytes in angle brackets
|
||||
//! (`< 3 0a0b0c >`, raw bytes). The set's `/version` comes first, and its `/name` is hexadecimal
|
||||
//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N`
|
||||
//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with
|
||||
//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was
|
||||
//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal
|
||||
//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
|
||||
//! and a step's `/parameterCount` give how many actions, steps and recorded values follow.
|
||||
//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting
|
||||
//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post
|
||||
//! "Made a two-way aia to json converter"
|
||||
//! (https://community.adobe.com/t5/illustrator-discussions/made-a-two-way-aia-to-json-converter/m-p/13751909),
|
||||
//! sttk3's article on names as UTF-8 hexadecimal
|
||||
//! (https://sttk3.com/blog/tips/illustrator/dynamic-generate-action.html), and the MIT-licensed
|
||||
//! reader in zachshallbetter/adobe-mcp (https://github.com/zachshallbetter/adobe-mcp). The raw form
|
||||
//! follows the forum thread "Creating a dynamic action"
|
||||
//! (https://community.adobe.com/questions-652/creating-a-dynamic-action-to-use-with-app-doscript-method-814406).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
|
||||
|
||||
/// The most bytes of a file read.
|
||||
const MAX_BYTES: usize = 8 << 20;
|
||||
/// The most bytes taken in: [`MAX_BYTES`] after a byte order mark, and one more that shows the text
|
||||
/// goes on.
|
||||
const READ_LIMIT: usize = MAX_BYTES + 4;
|
||||
/// The most blocks open at once.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most actions read.
|
||||
const MAX_ACTIONS: usize = 1000;
|
||||
/// The most steps read in one action.
|
||||
const MAX_STEPS: usize = 10_000;
|
||||
/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and
|
||||
/// the answer holds an object for each.
|
||||
const MAX_SET_STEPS: usize = 100_000;
|
||||
/// The longest name kept (bytes).
|
||||
const MAX_NAME: usize = 1024;
|
||||
/// The most tokens listed as unread.
|
||||
const MAX_UNREAD: usize = 1000;
|
||||
/// The longest unread token shown (characters).
|
||||
const UNREAD_SHOWN: usize = 80;
|
||||
|
||||
/// The extensions of action sets other apps save.
|
||||
pub const EXTS: &[&str] = &["aia"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "actionSet.read",
|
||||
"Read Action Set File",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
|
||||
always,
|
||||
read
|
||||
)]
|
||||
}
|
||||
|
||||
/// A step of an action: an `/event-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaStep {
|
||||
/// Its `/internalName`.
|
||||
pub name: String,
|
||||
/// Its `/localizedName`, if it has one.
|
||||
pub label: Option<String>,
|
||||
/// Its `/isOn`, if it has one.
|
||||
pub on: Option<i64>,
|
||||
/// How many `/parameter-N` blocks it has.
|
||||
pub params: usize,
|
||||
/// Its `/parameterCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The line its block opens on (from 1).
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// An action: an `/action-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaAction {
|
||||
pub name: String,
|
||||
pub steps: Vec<AiaStep>,
|
||||
/// Its `/eventCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
}
|
||||
|
||||
/// An action set read from text.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaSet {
|
||||
pub version: i64,
|
||||
/// The set's `/name`, if it has one.
|
||||
pub name: Option<String>,
|
||||
pub actions: Vec<AiaAction>,
|
||||
/// Its `/actionCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The tokens that weren't read, with their lines.
|
||||
pub unread: Vec<(usize, String)>,
|
||||
/// A cap stopped the reading or cut a name, the text ends inside a block or a value or after a
|
||||
/// field's name, its counts differ from the actions, steps and recorded values read (a negative
|
||||
/// count, one too large for an `i64` and one that isn't a number always differ), or a hexadecimal
|
||||
/// name, label or recorded `/value` isn't as many bytes as its count says.
|
||||
pub truncated: bool,
|
||||
/// How many steps were read in all the actions.
|
||||
steps: usize,
|
||||
}
|
||||
|
||||
/// A token of the text.
|
||||
enum Token {
|
||||
/// A slash name.
|
||||
Name(Vec<u8>),
|
||||
/// An integer; `None` when it doesn't fit an `i64`.
|
||||
Int(Option<i64>),
|
||||
/// Text in parentheses, a backslash taking the next byte as it is.
|
||||
Text(Vec<u8>),
|
||||
/// The bytes of `[ count hex… ]`; `None` when the hexadecimal digits don't make whole bytes or
|
||||
/// as many bytes as the count says.
|
||||
Hex(Option<Vec<u8>>),
|
||||
/// `< count hex… >`.
|
||||
Raw,
|
||||
Open,
|
||||
Close,
|
||||
/// Anything else, as written.
|
||||
Other(Vec<u8>),
|
||||
}
|
||||
|
||||
/// The tokens of `text`, each with its line.
|
||||
struct Tokens<'a> {
|
||||
text: &'a [u8],
|
||||
at: usize,
|
||||
line: usize,
|
||||
/// The text ended inside a value in parentheses, square brackets or angle brackets.
|
||||
unclosed: bool,
|
||||
}
|
||||
|
||||
impl<'a> Tokens<'a> {
|
||||
/// Past one byte, counting a line at LF, at CR alone, and once for CRLF.
|
||||
fn step(&mut self) -> Option<u8> {
|
||||
let b = *self.text.get(self.at)?;
|
||||
if b == b'\n' || b == b'\r' && self.text.get(self.at + 1) != Some(&b'\n') {
|
||||
self.line += 1;
|
||||
}
|
||||
self.at += 1;
|
||||
Some(b)
|
||||
}
|
||||
|
||||
/// The bytes up to `end` (not taken in); `None` when the text ends first.
|
||||
fn until(&mut self, end: u8) -> Option<&'a [u8]> {
|
||||
let (text, start) = (self.text, self.at);
|
||||
while text.get(self.at).is_some_and(|&b| b != end) {
|
||||
self.step();
|
||||
}
|
||||
let inside = text.get(start..self.at)?;
|
||||
text.get(self.at)?;
|
||||
self.at += 1;
|
||||
Some(inside)
|
||||
}
|
||||
|
||||
fn next_token(&mut self) -> Option<(usize, Token)> {
|
||||
while self.text.get(self.at).is_some_and(|&b| b.is_ascii_whitespace() || b == 0) {
|
||||
self.step();
|
||||
}
|
||||
let line = self.line;
|
||||
let b = *self.text.get(self.at)?;
|
||||
let ends = |b: u8| b.is_ascii_whitespace() || b == 0 || b"{}[]()<>/".contains(&b);
|
||||
let token = match b {
|
||||
b'{' | b'}' => {
|
||||
self.at += 1;
|
||||
if b == b'{' { Token::Open } else { Token::Close }
|
||||
}
|
||||
b'(' => {
|
||||
self.at += 1;
|
||||
let (mut text, mut depth) = (vec![], 0usize);
|
||||
self.unclosed = true;
|
||||
while let Some(c) = self.step() {
|
||||
match c {
|
||||
b'\\' => text.extend(self.step()),
|
||||
b'(' => {
|
||||
depth += 1;
|
||||
text.push(c);
|
||||
}
|
||||
b')' if depth == 0 => {
|
||||
self.unclosed = false;
|
||||
break;
|
||||
}
|
||||
b')' => {
|
||||
depth -= 1;
|
||||
text.push(c);
|
||||
}
|
||||
_ => text.push(c),
|
||||
}
|
||||
}
|
||||
Token::Text(text)
|
||||
}
|
||||
b'[' | b'<' => {
|
||||
self.at += 1;
|
||||
let close = if b == b'[' { b']' } else { b'>' };
|
||||
let inside = self.until(close);
|
||||
self.unclosed = inside.is_none();
|
||||
let inside = inside.unwrap_or_default().to_vec();
|
||||
if b == b'<' {
|
||||
Token::Raw
|
||||
} else {
|
||||
// The first word is the byte count; the bytes follow in one or more words.
|
||||
let mut words = inside.split(|c| c.is_ascii_whitespace()).filter(|w| !w.is_empty());
|
||||
let count = words.next().and_then(|w| std::str::from_utf8(w).ok()).and_then(|w| w.parse::<usize>().ok());
|
||||
let digits: Vec<u8> = words.flatten().copied().collect();
|
||||
Token::Hex(hex_bytes(&digits).filter(|b| Some(b.len()) == count))
|
||||
}
|
||||
}
|
||||
b'/' => {
|
||||
self.at += 1;
|
||||
let start = self.at;
|
||||
while self.text.get(self.at).is_some_and(|&c| !ends(c)) {
|
||||
self.at += 1;
|
||||
}
|
||||
Token::Name(self.text.get(start..self.at).unwrap_or_default().to_vec())
|
||||
}
|
||||
_ => {
|
||||
let start = self.at;
|
||||
while self.text.get(self.at).is_some_and(|&c| !ends(c)) {
|
||||
self.at += 1;
|
||||
}
|
||||
// Always past at least one byte.
|
||||
self.at = self.at.max(start + 1);
|
||||
let word = self.text.get(start..self.at).unwrap_or_default();
|
||||
let number = word.strip_prefix(b"-").or_else(|| word.strip_prefix(b"+")).unwrap_or(word);
|
||||
if !number.is_empty() && number.iter().all(u8::is_ascii_digit) {
|
||||
Token::Int(std::str::from_utf8(word).ok().and_then(|s| s.parse().ok()))
|
||||
} else {
|
||||
Token::Other(word.to_vec())
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((line, token))
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes hexadecimal `digits` stand for, two digits a byte.
|
||||
fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
|
||||
let nibble = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok());
|
||||
if !digits.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
digits.chunks(2).map(|pair| Some((nibble(*pair.first()?)? << 4) | nibble(*pair.get(1)?)?)).collect()
|
||||
}
|
||||
|
||||
/// What a block is.
|
||||
enum Kind {
|
||||
Action,
|
||||
Step,
|
||||
Param,
|
||||
/// A block that isn't read, or one past a cap.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// `name` ends with `-` and a number after `prefix`, as `/action-1` does.
|
||||
fn numbered(name: &[u8], prefix: &[u8]) -> bool {
|
||||
name.strip_prefix(prefix).is_some_and(|n| !n.is_empty() && n.iter().all(u8::is_ascii_digit))
|
||||
}
|
||||
|
||||
/// A name as text: at most [`MAX_NAME`] bytes, read as UTF-8 with replacement characters.
|
||||
fn name_text(name: &[u8], set: &mut AiaSet) -> String {
|
||||
if name.len() > MAX_NAME {
|
||||
set.truncated = true;
|
||||
}
|
||||
let mut s = String::from_utf8_lossy(name.get(..MAX_NAME).unwrap_or(name)).into_owned();
|
||||
// A character cut at the limit reads as one replacement character.
|
||||
if name.len() > MAX_NAME && s.ends_with('\u{FFFD}') {
|
||||
s.pop();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// How the unread list shows a value in square brackets that isn't as many bytes as its count says.
|
||||
const BAD_HEX: &str = "[ … ] (not the hexadecimal bytes its count says)";
|
||||
|
||||
/// List a token that isn't read.
|
||||
fn unread(set: &mut AiaSet, line: usize, text: impl AsRef<[u8]>) {
|
||||
if set.unread.len() < MAX_UNREAD {
|
||||
let text: String = String::from_utf8_lossy(text.as_ref()).chars().take(UNREAD_SHOWN).collect();
|
||||
set.unread.push((line, text));
|
||||
}
|
||||
}
|
||||
|
||||
/// What the block `name` that opens on `line` inside the blocks `stack` is: a new action, step or
|
||||
/// recorded value of `set`, or a block that isn't read (listed when it is out of place).
|
||||
fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kind {
|
||||
match stack.last() {
|
||||
_ if stack.len() >= MAX_DEPTH => {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
None if numbered(name, b"action-") => {
|
||||
if set.actions.len() < MAX_ACTIONS {
|
||||
set.actions.push(AiaAction::default());
|
||||
Kind::Action
|
||||
} else {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
Some(Kind::Action) if numbered(name, b"event-") => match set.actions.last_mut() {
|
||||
Some(a) if a.steps.len() < MAX_STEPS && set.steps < MAX_SET_STEPS => {
|
||||
a.steps.push(AiaStep { line, ..AiaStep::default() });
|
||||
set.steps += 1;
|
||||
Kind::Step
|
||||
}
|
||||
_ => {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
},
|
||||
Some(Kind::Step) if numbered(name, b"parameter-") => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.params += 1;
|
||||
}
|
||||
Kind::Param
|
||||
}
|
||||
Some(Kind::Param | Kind::Other) => Kind::Other,
|
||||
_ => {
|
||||
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the field `name` of the block `kind` (the set when `None`) to the hexadecimal text `bytes`
|
||||
/// on `line`: the set's or an action's `/name`, or a step's `/localizedName`.
|
||||
fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Option<Vec<u8>>, line: usize) {
|
||||
let Some(bytes) = bytes else {
|
||||
set.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
return;
|
||||
};
|
||||
match (kind, name) {
|
||||
(None, Some(b"name")) => set.name = Some(name_text(&bytes, set)),
|
||||
(Some(Kind::Action), Some(b"name")) => {
|
||||
let text = name_text(&bytes, set);
|
||||
if let Some(a) = set.actions.last_mut() {
|
||||
a.name = text;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"localizedName")) => {
|
||||
let text = name_text(&bytes, set);
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.label = Some(text);
|
||||
}
|
||||
}
|
||||
(_, Some(_)) => {}
|
||||
(_, None) => unread(set, line, "[ … ]"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count
|
||||
/// says.
|
||||
fn check_value(set: &mut AiaSet, bytes: Option<Vec<u8>>, line: usize) {
|
||||
if bytes.is_none() {
|
||||
set.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `set` truncated when the field `name` of the block `kind` (the set when `None`) is a count
|
||||
/// (the set's `/actionCount`, an action's `/eventCount` or a step's `/parameterCount`) whose value is
|
||||
/// not a number that fits an `i64`.
|
||||
fn bad_count(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>) {
|
||||
if matches!((kind, name), (None, Some(b"actionCount")) | (Some(Kind::Action), Some(b"eventCount")) | (Some(Kind::Step), Some(b"parameterCount")))
|
||||
{
|
||||
set.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the field `name` of the block `kind` (the set when `None`) to the integer `value` on `line`:
|
||||
/// the set's `/actionCount`, an action's `/eventCount`, a step's `/parameterCount`, or a step's
|
||||
/// `/isOn`. A count too large for an `i64` marks the set truncated.
|
||||
fn set_int(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, value: Option<i64>, line: usize) {
|
||||
if value.is_none() {
|
||||
bad_count(set, kind, name);
|
||||
}
|
||||
match (kind, name) {
|
||||
(None, Some(b"actionCount")) => set.declared = value,
|
||||
(Some(Kind::Action), Some(b"eventCount")) => {
|
||||
if let Some(a) = set.actions.last_mut() {
|
||||
a.declared = value;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"parameterCount")) => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.declared = value;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"isOn")) => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.on = value;
|
||||
}
|
||||
}
|
||||
(_, Some(_)) => {}
|
||||
(_, None) => unread(set, line, value.map_or_else(|| "(a number too large)".to_string(), |v| v.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read an action set saved as text. An error when the text isn't one: it doesn't start with
|
||||
/// `/version` and an integer.
|
||||
pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
|
||||
let mut set = AiaSet::default();
|
||||
let text = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
|
||||
let text = match text.get(..MAX_BYTES) {
|
||||
Some(head) if text.len() > MAX_BYTES => {
|
||||
set.truncated = true;
|
||||
head
|
||||
}
|
||||
_ => text,
|
||||
};
|
||||
let mut tokens = Tokens { text, at: 0, line: 1, unclosed: false };
|
||||
match (tokens.next_token(), tokens.next_token()) {
|
||||
(Some((_, Token::Name(n))), Some((_, Token::Int(Some(v))))) if n == b"version" => set.version = v,
|
||||
_ => return Err("not an action set: the text doesn't start with /version and a number".into()),
|
||||
}
|
||||
let mut stack: Vec<Kind> = vec![];
|
||||
// A slash name waiting for its value or its `{`: (line, name).
|
||||
let mut pending: Option<(usize, Vec<u8>)> = None;
|
||||
while let Some((line, token)) = tokens.next_token() {
|
||||
let in_step = matches!(stack.last(), Some(Kind::Step));
|
||||
let field = |pending: &mut Option<(usize, Vec<u8>)>| pending.take().map(|(_, n)| n);
|
||||
match token {
|
||||
Token::Name(name) => {
|
||||
if let Some((l, n)) = pending.replace((line, name)) {
|
||||
bad_count(&mut set, stack.last(), Some(&n));
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
}
|
||||
Token::Open => {
|
||||
let (l, name) = pending.take().unwrap_or((line, vec![]));
|
||||
bad_count(&mut set, stack.last(), Some(&name));
|
||||
let kind = open_block(&mut set, &stack, &name, l);
|
||||
stack.push(kind);
|
||||
}
|
||||
Token::Close => {
|
||||
if let Some((l, n)) = pending.take() {
|
||||
bad_count(&mut set, stack.last(), Some(&n));
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
if stack.pop().is_none() {
|
||||
unread(&mut set, line, "}");
|
||||
}
|
||||
}
|
||||
Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => {
|
||||
if field(&mut pending).as_deref() == Some(b"value".as_slice()) {
|
||||
check_value(&mut set, bytes, line);
|
||||
}
|
||||
}
|
||||
// The other values inside a recorded value, or a block that isn't read.
|
||||
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
|
||||
pending = None;
|
||||
}
|
||||
Token::Hex(bytes) => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
set_hex(&mut set, stack.last(), name.as_deref(), bytes, line);
|
||||
}
|
||||
Token::Text(t) => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
match name {
|
||||
Some(n) if in_step && n == b"internalName" => {
|
||||
let name = name_text(&t, &mut set);
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.name = name;
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
None => unread(&mut set, line, [b"(".as_slice(), &t, b")"].concat()),
|
||||
}
|
||||
}
|
||||
Token::Int(v) => {
|
||||
let name = field(&mut pending);
|
||||
set_int(&mut set, stack.last(), name.as_deref(), v, line);
|
||||
}
|
||||
Token::Raw => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
if name.is_none() {
|
||||
unread(&mut set, line, "< … >");
|
||||
}
|
||||
}
|
||||
Token::Other(word) => {
|
||||
// A real number, or another word as a field's value.
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
if name.is_none() {
|
||||
unread(&mut set, line, word);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The text ends after a field's name, before its value.
|
||||
if let Some((l, n)) = pending {
|
||||
set.truncated = true;
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
// An unclosed value is the last token: it takes the rest of the text.
|
||||
if tokens.unclosed {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, "a value not closed at the end");
|
||||
}
|
||||
if !stack.is_empty() {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, format!("blocks left open at the end: {}", stack.len()));
|
||||
}
|
||||
// Not as many actions, steps or recorded values as the counts give; a negative count never matches.
|
||||
let differs = |declared: Option<i64>, read: usize| declared.is_some_and(|d| !usize::try_from(d).is_ok_and(|d| d == read));
|
||||
let step_differs = |a: &AiaAction| a.steps.iter().any(|s| differs(s.declared, s.params));
|
||||
if differs(set.declared, set.actions.len()) || set.actions.iter().any(|a| differs(a.declared, a.steps.len()) || step_differs(a)) {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, "not as many actions, steps or recorded values as the counts give");
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
fn read(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "actionSet.read";
|
||||
let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
|
||||
let name = text_param(p, "name", C)?;
|
||||
let bytes: std::borrow::Cow<[u8]> = match (path, data, b64) {
|
||||
(Some(path), None, None) => super::fileio::read_file_head(path, READ_LIMIT)?.into(),
|
||||
(None, Some(text), None) => text.as_bytes().get(..READ_LIMIT).unwrap_or(text.as_bytes()).into(),
|
||||
(None, None, Some(b64)) => super::scripts::decode_head(b64, READ_LIMIT).ok_or_else(|| bad(C, "bad dataBase64"))?.into(),
|
||||
_ => return Err(bad(C, "give exactly one of `path`, `data` and `dataBase64`")),
|
||||
};
|
||||
let set = read_aia(&bytes).map_err(EngineError::Other)?;
|
||||
let file = name.or(path).unwrap_or_default();
|
||||
let stem = std::path::Path::new(file).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = set.name.clone().filter(|n| !n.trim().is_empty()).unwrap_or(stem);
|
||||
let actions: Vec<Value> = set
|
||||
.actions
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let steps: Vec<Value> = a
|
||||
.steps
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let label = s.label.clone().filter(|l| !l.trim().is_empty());
|
||||
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line })
|
||||
})
|
||||
.collect();
|
||||
json!({ "name": a.name, "steps": steps })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"set": name,
|
||||
"version": set.version,
|
||||
"actions": actions,
|
||||
"unread": set.unread.iter().map(|(line, text)| json!({ "line": line, "text": text })).collect::<Vec<_>>(),
|
||||
"truncated": set.truncated,
|
||||
}))
|
||||
}
|
||||
@@ -1004,7 +1004,6 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
|
||||
drop(replace);
|
||||
Ok(runs)
|
||||
})?;
|
||||
Ok(json!({ "runs": runs, "font": family }))
|
||||
|
||||
@@ -45,7 +45,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, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row",
|
||||
"{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, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{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",
|
||||
"{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. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -126,7 +126,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, 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, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, 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}",
|
||||
"{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, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, 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); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's solid fill and stroke for this instance only, as the Eyedropper Options allow, and a sampled gradient or pattern, a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -551,12 +551,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
// 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, _| {
|
||||
// The objects that got a new topmost row of the kind: the series stores its paint even when the object showed it.
|
||||
let mut added = Vec::new();
|
||||
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 let Some(kind) = top_row_kind(&n.appearance, i + 1) {
|
||||
added.push((*id, kind));
|
||||
}
|
||||
if active == Some(*id) {
|
||||
above = Some(i + 1);
|
||||
}
|
||||
@@ -591,10 +596,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
} else {
|
||||
n.appearance.items.push(item);
|
||||
added.push((*id, fill));
|
||||
}
|
||||
if !fill {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(())
|
||||
})?;
|
||||
// A fill added above the active row becomes the active row; otherwise the rows above the new
|
||||
@@ -611,10 +623,12 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
ok()
|
||||
@@ -626,15 +640,66 @@ fn both_kinds(ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).collect()
|
||||
}
|
||||
|
||||
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost row has another opacity in `d` than
|
||||
/// in `before` (no row counts as opaque), for [`super::graph::capture_series_opacity`].
|
||||
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another opacity in `d`
|
||||
/// than in `before` (no row counts as opaque), for [`super::graph::capture_series_opacity`].
|
||||
fn top_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| {
|
||||
d.node(id).and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill).map(AppearanceItem::opacity)).unwrap_or(1.0)
|
||||
d.node(id)
|
||||
.and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill && it.visible()).map(AppearanceItem::opacity))
|
||||
.unwrap_or(1.0)
|
||||
};
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect()
|
||||
}
|
||||
|
||||
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another paint, or a
|
||||
/// stroke another weight, in `d` than in `before` (no row counts as no paint), for
|
||||
/// [`super::graph::capture_series_top_paints`].
|
||||
fn top_paint_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| d.node(id).map(|n| super::graph::shown_paint(n, fill));
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect()
|
||||
}
|
||||
|
||||
/// `rows` (each object with the kind of row) whose topmost visible row of that kind has paint: a command that wrote them
|
||||
/// replaces the paint another mark of the series left on the graph, even when the mark's own row comes out as it was.
|
||||
fn painted_rows(d: &vectorcraft_doc::Document, rows: impl IntoIterator<Item = (NodeId, bool)>) -> Vec<(NodeId, bool)> {
|
||||
rows.into_iter().filter(|(id, fill)| d.node(*id).is_some_and(|n| !super::graph::shown_paint(n, *fill).0.is_none())).collect()
|
||||
}
|
||||
|
||||
/// Store on the graph what an edit of `ids` (from `before` to `d`) leaves on the topmost visible fill and stroke of the
|
||||
/// series marks among them: a paint, weight or opacity that changed, and the paint (`paints`) and opacity (`opacities`) of
|
||||
/// the kinds of row the edit wrote, as (fill, stroke). With `top_only` the edit wrote the topmost row of each kind, which
|
||||
/// counts only when it is visible. Returns whether the stored paint changed.
|
||||
pub(super) fn capture_series_writes(
|
||||
before: &vectorcraft_doc::Document,
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
ids: &[NodeId],
|
||||
paints: (bool, bool),
|
||||
opacities: (bool, bool),
|
||||
top_only: bool,
|
||||
) -> bool {
|
||||
let top_shows = |d: &vectorcraft_doc::Document, id: NodeId, kind: bool| {
|
||||
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
|
||||
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(AppearanceItem::visible)
|
||||
};
|
||||
let written = |d: &vectorcraft_doc::Document, (fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> {
|
||||
let rows = ids.iter().flat_map(|id| [fill.then_some((*id, true)), stroke.then_some((*id, false))]).flatten();
|
||||
painted_rows(d, rows.filter(|(id, kind)| !top_only || top_shows(d, *id, *kind)))
|
||||
};
|
||||
let mut opacity_rows = top_opacity_changed(before, d, ids);
|
||||
opacity_rows.extend(written(d, opacities));
|
||||
let mut rows = top_paint_changed(before, d, ids);
|
||||
rows.extend(written(d, paints));
|
||||
let kept = super::graph::capture_series_opacity(d, &opacity_rows);
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
kept || painted
|
||||
}
|
||||
|
||||
/// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`.
|
||||
fn top_row_kind(ap: &Appearance, at: usize) -> Option<bool> {
|
||||
let fill = ap.items.get(at)?.is_fill();
|
||||
(ap.items.iter().rposition(|it| it.is_fill() == fill && it.visible()) == Some(at)).then_some(fill)
|
||||
}
|
||||
|
||||
/// Clear Appearance on `n`: no fill, no stroke, and the object's Opacity row back to Default. A
|
||||
/// group keeps no fill or stroke rows of its own.
|
||||
fn clear(n: &mut Node) {
|
||||
@@ -666,13 +731,19 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
to.appearance = ap;
|
||||
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
|
||||
super::object::snap_if_aligned(to);
|
||||
if !copy && let Some(n) = d.node_mut(source) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
let changed = if copy { vec![target] } else { vec![source, target] };
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
|
||||
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept))
|
||||
// The target last: on marks of one series, its paint is the one the series keeps.
|
||||
let mut rows = top_paint_changed(&before, d, &changed);
|
||||
rows.extend(painted_rows(d, both_kinds(&[target])));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
Ok(json!({ "source": source.0, "target": target.0 }))
|
||||
@@ -723,10 +794,12 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.blend = BlendMode::Normal;
|
||||
n.appearance.items.push(AppearanceItem::Stroke(st));
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
ok()
|
||||
@@ -752,10 +825,6 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
let Some(&idx) = at.first() else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let items = &n.appearance.items;
|
||||
if let Some(fill) = items.get(idx).map(AppearanceItem::is_fill).filter(|f| items.iter().rposition(|it| it.is_fill() == *f) == Some(idx)) {
|
||||
edited.push((*id, fill));
|
||||
}
|
||||
if p.get("weight").is_none()
|
||||
&& let Some(pa) = &paint
|
||||
{
|
||||
@@ -785,10 +854,27 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("visible").and_then(Value::as_bool) {
|
||||
*vis = v;
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
let items = &n.appearance.items;
|
||||
if let Some(fill) =
|
||||
items.get(idx).map(AppearanceItem::is_fill).filter(|f| items.iter().rposition(|it| it.is_fill() == *f && it.visible()) == Some(idx))
|
||||
{
|
||||
edited.push((*id, fill));
|
||||
}
|
||||
}
|
||||
// The graph keeps an opacity set on the topmost fill or stroke of its series art for when it is drawn again.
|
||||
let kept = p.get("opacity").and_then(Value::as_f64).is_some() && super::graph::capture_series_opacity(d, &edited);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
// The graph keeps an opacity, paint or weight set on the topmost visible fill or stroke of its series art for when
|
||||
// it is drawn again, and hiding or showing a row changes which row that is.
|
||||
let mut opacities = top_opacity_changed(&before, d, &ids);
|
||||
if p.get("opacity").and_then(Value::as_f64).is_some() {
|
||||
opacities.extend(edited.iter().copied());
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &opacities);
|
||||
// A weight goes with the paint of its stroke; a stroke without paint leaves the series' paint alone.
|
||||
let written = edited.iter().copied().filter(|(_, fill)| paint.is_some() || (!*fill && p.get("weight").is_some()));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, written));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
if let Some(pa) = &paint {
|
||||
s.remember_paint(pa);
|
||||
@@ -829,10 +915,12 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for &i in idx.iter().rev() {
|
||||
n.appearance.remove_item(i);
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count()));
|
||||
ok()
|
||||
@@ -862,6 +950,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p, C)?);
|
||||
s.edit("Duplicate Item", |d, _| {
|
||||
let mut any = false;
|
||||
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
|
||||
// showed it.
|
||||
let mut added = Vec::new();
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let has_contents = n.contents_label().is_some();
|
||||
@@ -877,9 +968,11 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if active == Some(*id) {
|
||||
active_at = Some(at);
|
||||
}
|
||||
let count = copies.len();
|
||||
for (k, item) in copies.into_iter().enumerate() {
|
||||
ap.insert_item(at + k, item);
|
||||
}
|
||||
added.extend((at..at + count).filter_map(|k| top_row_kind(ap, k)).map(|kind| (*id, kind)));
|
||||
if let Some(c) = contents.filter(|_| has_contents) {
|
||||
ap.set_contents_at(c);
|
||||
}
|
||||
@@ -893,6 +986,10 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(item) = ap.items.get(i).cloned() {
|
||||
first_at.get_or_insert(i + 1);
|
||||
ap.insert_item(i + 1, item);
|
||||
// Copies below this one go in lower down, so a copy that is the topmost row of its kind stays it.
|
||||
if let Some(kind) = top_row_kind(ap, i + 1) {
|
||||
added.push((*id, kind));
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
@@ -901,6 +998,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("no item at index {}", idx[0])));
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(())
|
||||
})?;
|
||||
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
|
||||
@@ -918,11 +1018,26 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects.
|
||||
fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = require_targets(s, p, "appearance.showAllHidden")?;
|
||||
let before = s.doc()?.doc.clone();
|
||||
let ids = s.edit("Show All Hidden Attributes", |d, _| {
|
||||
let shown: Vec<NodeId> = roots.iter().copied().filter(|id| d.node_mut(*id).is_some_and(|n| n.appearance.show_all())).collect();
|
||||
let shown: Vec<NodeId> = roots
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
d.node_mut(*id).is_some_and(|n| {
|
||||
let shown = n.appearance.show_all();
|
||||
if shown {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
shown
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if shown.is_empty() {
|
||||
return Err(EngineError::Other("Show All Hidden Attributes: nothing is hidden".into()));
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown));
|
||||
super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown));
|
||||
Ok(shown)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
@@ -962,7 +1077,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
// The moved row stays the active one; the rows it passed shift by one.
|
||||
s.remap_appearance_item(&ids, |a| {
|
||||
@@ -1006,7 +1122,8 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<V
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids));
|
||||
Ok(count_changed(d, &before, ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, ids));
|
||||
Ok(count_changed(d, &before, ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
let m = idx.len();
|
||||
let landed = first_landed.unwrap_or(to);
|
||||
@@ -1069,6 +1186,42 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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))?;
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection takes the clicked
|
||||
// object's solid fill and stroke, as the Eyedropper Options allow, for this instance only. A
|
||||
// gradient or pattern sampled for it, a source that is not a path, compound path or type (a
|
||||
// symbol instance's own appearance is empty), and options that pick up neither color are
|
||||
// refused, and the paint defaults stay as they are. A path of a compound path stands for the
|
||||
// compound path, which holds the paint.
|
||||
if !reverse
|
||||
&& !append
|
||||
&& !defaults_only
|
||||
&& p.get("ids").is_none()
|
||||
&& let Some((id, path)) = super::brushsym::selected_part(s)?
|
||||
{
|
||||
let d = &s.doc()?.doc;
|
||||
let src = Arc::new(d.node(super::path::compound_or_self(d, clicked)).ok_or(EngineError::NoNode(clicked))?.clone());
|
||||
let (fill, stroke) = (super::paint::proxy_paint(&src, false, None), super::paint::proxy_paint(&src, true, None));
|
||||
let a = attrs.appearance;
|
||||
if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src)
|
||||
|| !(a.fill.color || a.stroke.color)
|
||||
|| (a.fill.color && !super::paint::part_takes(&fill))
|
||||
|| (a.stroke.color && !super::paint::part_takes(&stroke))
|
||||
{
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
super::brushsym::edit_part(s, id, &path, "Eyedropper", |o| {
|
||||
if a.fill.color {
|
||||
o.fill = Some(fill);
|
||||
}
|
||||
if a.stroke.color {
|
||||
o.stroke = Some(stroke);
|
||||
}
|
||||
})?;
|
||||
// The clicked object becomes the Eyedropper's sample, and new art takes its paint.
|
||||
Picked::of(&src).to_defaults(s, &attrs.appearance);
|
||||
s.eyedropper_sample = Some(src);
|
||||
return Ok(json!({ "ids": [id.0] }));
|
||||
}
|
||||
let range = if !defaults_only && !reverse && !append && p.get("ids").is_none() {
|
||||
super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b)
|
||||
} else {
|
||||
@@ -1160,8 +1313,41 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
picked.apply(n, &attrs, append);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &targets));
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept))
|
||||
// The paints the pick wrote, with a weight going with the paint of its stroke, as in `set_item`. `append` adds
|
||||
// only the colors of the visible rows the source has.
|
||||
let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke);
|
||||
let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind);
|
||||
let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let (paints, opacities) = if append {
|
||||
let rows = (fill.color && source_shows(true), stroke.color && source_shows(false));
|
||||
(rows, rows)
|
||||
} else {
|
||||
(
|
||||
(fill.color, stroke.color || (stroke.weight && source_has(false))),
|
||||
(fill.transparency && source_has(true), stroke.transparency && source_has(false)),
|
||||
)
|
||||
};
|
||||
// A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows.
|
||||
let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL);
|
||||
let top_shows = |id: NodeId, kind: bool| {
|
||||
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
|
||||
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible())
|
||||
};
|
||||
let written = |(fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> {
|
||||
targets
|
||||
.iter()
|
||||
.flat_map(|id| [fill.then_some((*id, true)), stroke.then_some((*id, false))])
|
||||
.flatten()
|
||||
.filter(|(id, kind)| rows_written || top_shows(*id, *kind))
|
||||
.collect()
|
||||
};
|
||||
let mut opacity_rows = top_opacity_changed(&before, d, &targets);
|
||||
opacity_rows.extend(painted_rows(d, written(opacities)));
|
||||
let mut rows = top_paint_changed(&before, d, &targets);
|
||||
rows.extend(painted_rows(d, written(paints)));
|
||||
let kept = super::graph::capture_series_opacity(d, &opacity_rows);
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted))
|
||||
})?;
|
||||
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -1243,6 +1429,7 @@ impl Picked {
|
||||
let placed = self.placed(n.geometric_bounds());
|
||||
n.appearance.items.extend(placed.items.into_iter().filter(|it| if it.is_fill() { ap.fill.color } else { ap.stroke.color }));
|
||||
n.appearance.effects.extend(placed.effects);
|
||||
super::object::snap_if_aligned(n);
|
||||
return;
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
@@ -1266,6 +1453,7 @@ impl Picked {
|
||||
} else {
|
||||
focal_attrs(&mut n.appearance, &placed, ap);
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,17 @@
|
||||
//! settings Export for Screens shares (`document.exportSettings`). File → Export Selection collects
|
||||
//! the selection this way and opens Export for Screens on its Assets tab (a UI command).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::fileio::{SCREEN_SETTINGS_KEYS, check_screen_settings, export_crop, export_screens, store_screen_settings, with_screen_export_preset};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param};
|
||||
use super::fileio::{
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
|
||||
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
|
||||
};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
|
||||
|
||||
/// The longest asset name kept (characters).
|
||||
const MAX_NAME: usize = 255;
|
||||
@@ -39,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Assets",
|
||||
[],
|
||||
None,
|
||||
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included)}]} the Asset Export panel's assets, in order",
|
||||
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -48,10 +53,37 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default all), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
"{assets?: [asset id…] (default all but the 3D assets, which assets.export3D writes), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
cmd!(
|
||||
"assets.add3D",
|
||||
"Export 3D Object",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}",
|
||||
has_doc,
|
||||
add_3d
|
||||
),
|
||||
cmd!(
|
||||
"assets.set3DFormat",
|
||||
"3D Export Format",
|
||||
[],
|
||||
None,
|
||||
"{assets: [asset id…], format: usda|usdz|gltf|obj} the mesh format 3D assets export to (Asset Export's Format for a 3D asset) → {changed: n}",
|
||||
has_doc,
|
||||
set_3d_format
|
||||
),
|
||||
cmd!(
|
||||
"assets.export3D",
|
||||
"Export 3D Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
has_doc,
|
||||
export_3d
|
||||
),
|
||||
cmd!(
|
||||
"assets.settings.set",
|
||||
"Asset Export Settings",
|
||||
@@ -115,7 +147,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if name.is_some() && sets.len() > 1 {
|
||||
return Err(bad(C, "a name names one asset: give multiple: false, or one object"));
|
||||
}
|
||||
let existing = |d: &vectorcraft_doc::Document, nodes: &[NodeId]| d.assets.iter().find(|a| a.nodes == nodes).map(|a| a.id);
|
||||
// A 3D asset of the same art is another asset.
|
||||
let existing =
|
||||
|d: &vectorcraft_doc::Document, nodes: &[NodeId]| d.assets.iter().find(|a| a.nodes == nodes && a.format_3d.is_none()).map(|a| a.id);
|
||||
let d = &s.doc()?.doc;
|
||||
// Nothing new: no undo step.
|
||||
if sets.iter().all(|set| existing(d, set).is_some()) {
|
||||
@@ -134,7 +168,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let name = name.clone().or(own).unwrap_or_else(|| d.next_asset_name());
|
||||
let id = d.alloc_id().0;
|
||||
d.assets.push(ExportAsset { id, name, nodes });
|
||||
d.assets.push(ExportAsset { id, name, nodes, format_3d: None });
|
||||
out.push(id);
|
||||
added += 1;
|
||||
}
|
||||
@@ -142,6 +176,162 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The format of param `format` of command `cmd` ([`FORMATS_3D`]), `default` when it is not given.
|
||||
fn format_3d_param(p: &Value, cmd: &str, default: Option<&str>) -> Result<String> {
|
||||
match (p.get("format"), default) {
|
||||
(None, Some(d)) => Ok(d.to_string()),
|
||||
(Some(Value::String(f)), _) if FORMATS_3D.contains(&f.as_str()) => Ok(f.clone()),
|
||||
_ => {
|
||||
let key = "format";
|
||||
Err(bad(cmd, format!("`{key}` must be one of {}", FORMATS_3D.join(", "))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset ids of param `key` of command `cmd`, each a 3D asset of `d`.
|
||||
fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
|
||||
let ids = asset_ids(p, key, cmd)?;
|
||||
for id in &ids {
|
||||
match d.asset(*id) {
|
||||
None => return Err(bad(cmd, "no such assets (see assets.list)")),
|
||||
Some(a) if a.format_3d.is_none() => return Err(bad(cmd, format!("asset {id} isn't a 3D asset"))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn add_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.add3D";
|
||||
let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?;
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? };
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select an object with a 3D effect (or give its ids)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let mut ids = d.paint_order(ids);
|
||||
ids.dedup();
|
||||
for id in &ids {
|
||||
let n = d.node(*id).ok_or_else(|| bad(C, format!("no such object {0}", id.0)))?;
|
||||
if let Err(e) = vectorcraft_render::effects::three_d_meshes(n) {
|
||||
let what = n.name.clone().unwrap_or_else(|| format!("#{}", id.0));
|
||||
return Err(bad(C, format!("{what} can't be exported in 3D: {e}")));
|
||||
}
|
||||
}
|
||||
let existing = |d: &vectorcraft_doc::Document, id: NodeId| d.assets.iter().find(|a| a.nodes == [id] && a.format_3d.is_some()).map(|a| a.id);
|
||||
// Nothing new: no undo step.
|
||||
if ids.iter().all(|id| existing(d, *id).is_some()) {
|
||||
return Ok(json!({ "assets": ids.iter().filter_map(|id| existing(d, *id)).collect::<Vec<_>>(), "added": 0 }));
|
||||
}
|
||||
s.edit("Export 3D Object", |d, _| {
|
||||
let (mut out, mut added) = (vec![], 0);
|
||||
for node in ids {
|
||||
if let Some(id) = existing(d, node) {
|
||||
out.push(id);
|
||||
continue;
|
||||
}
|
||||
let name = d.node(node).and_then(|n| n.name.as_deref()).and_then(clean_name).unwrap_or_else(|| d.next_asset_name());
|
||||
let id = d.alloc_id().0;
|
||||
d.assets.push(ExportAsset { id, name, nodes: vec![node], format_3d: Some(format.clone()) });
|
||||
out.push(id);
|
||||
added += 1;
|
||||
}
|
||||
Ok(json!({ "assets": out, "added": added }))
|
||||
})
|
||||
}
|
||||
|
||||
fn set_3d_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.set3DFormat";
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = three_d_asset_ids(d, p, "assets", C)?;
|
||||
let format = format_3d_param(p, C, None)?;
|
||||
let changed = d.assets.iter().filter(|a| ids.contains(&a.id) && a.format_3d.as_deref() != Some(format.as_str())).count();
|
||||
// Nothing changes: no undo step.
|
||||
if changed == 0 {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
s.edit("3D Export Format", |d, _| {
|
||||
for a in d.assets.iter_mut().filter(|a| ids.contains(&a.id)) {
|
||||
a.format_3d = Some(format.clone());
|
||||
}
|
||||
Ok(json!({ "changed": changed }))
|
||||
})
|
||||
}
|
||||
|
||||
fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.export3D";
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = if p.get("assets").is_some_and(|v| !v.is_null()) {
|
||||
three_d_asset_ids(d, p, "assets", C)?
|
||||
} else {
|
||||
d.assets.iter().filter(|a| a.format_3d.is_some()).map(|a| a.id).collect()
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "no 3D assets yet: collect an object with a 3D effect first (assets.add3D)"));
|
||||
}
|
||||
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty());
|
||||
let zip = switch_or(p, "zip", false, C)?;
|
||||
// Every file's name, compared without case: a later file that would take one gets -2, -3…
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
let mut files: Vec<(String, Vec<u8>)> = vec![];
|
||||
for id in ids {
|
||||
let Some(a) = d.asset(id) else { continue };
|
||||
let format = a.format_3d.as_deref().unwrap_or(DEFAULT_FORMAT_3D);
|
||||
let mut parts = vec![];
|
||||
for node in &a.nodes {
|
||||
let n = d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))?;
|
||||
let what = &a.name;
|
||||
parts.extend(vectorcraft_render::effects::three_d_meshes(n).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?);
|
||||
}
|
||||
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
|
||||
let mut stem = base.clone();
|
||||
let mut k = 1;
|
||||
loop {
|
||||
let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?;
|
||||
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
|
||||
break;
|
||||
}
|
||||
k += 1;
|
||||
stem = format!("{base}-{k}");
|
||||
}
|
||||
let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?;
|
||||
taken.extend(made.iter().map(|(n, _)| n.to_lowercase()));
|
||||
files.extend(made);
|
||||
}
|
||||
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
|
||||
if zip {
|
||||
let archive = super::fileio::zip::store(&files).map_err(|e| bad(C, e))?;
|
||||
// "-3D" keeps it apart from the picture assets' ZIP, which is named after the document.
|
||||
let name = Some(safe_file_name(&d.title)).filter(|t| !t.is_empty()).map_or_else(|| "3D Assets.zip".into(), |t| format!("{t}-3D.zip"));
|
||||
return match folder {
|
||||
Some(dir) => {
|
||||
create_dir(dir)?;
|
||||
let path = format!("{dir}/{name}");
|
||||
write_file(&path, &archive)?;
|
||||
Ok(json!({ "path": path, "bytes": archive.len(), "files": names }))
|
||||
}
|
||||
None => Ok(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(&archive), "bytes": archive.len(), "files": names })),
|
||||
};
|
||||
}
|
||||
match folder {
|
||||
Some(dir) => {
|
||||
create_dir(dir)?;
|
||||
let mut written = vec![];
|
||||
for (name, bytes) in &files {
|
||||
let path = format!("{dir}/{name}");
|
||||
write_file(&path, bytes)?;
|
||||
written.push(path);
|
||||
}
|
||||
Ok(json!({ "files": written }))
|
||||
}
|
||||
None => {
|
||||
let files: Vec<Value> =
|
||||
files.iter().map(|(name, bytes)| json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) })).collect();
|
||||
Ok(json!({ "files": files }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset ids of param `key`.
|
||||
fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
|
||||
let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?;
|
||||
@@ -186,6 +376,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"name": a.name,
|
||||
"nodes": a.nodes.iter().map(|n| n.0).collect::<Vec<_>>(),
|
||||
"bounds": bounds.map(|b| [b.x0, b.y0, b.width(), b.height()]),
|
||||
"format3D": a.format_3d,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -227,8 +418,10 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if q.get("subfolders").and_then(Value::as_bool) == Some(false) && p.get("folders").is_none() {
|
||||
q.insert("folders".into(), json!("none"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
// 3D assets are written as mesh files, by assets.export3D: the export refuses one it is given.
|
||||
if !q.contains_key("assets") {
|
||||
let all: Vec<u64> = s.doc()?.doc.assets.iter().map(|a| a.id).collect();
|
||||
let all: Vec<u64> = d.assets.iter().filter(|a| a.format_3d.is_none()).map(|a| a.id).collect();
|
||||
if all.is_empty() {
|
||||
return Err(bad(C, "no assets yet: collect art for export first (assets.add)"));
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ use super::{
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
/// Whether Reset Transformation changes a symbol instance.
|
||||
pub use symbols::reset_transformation_changes;
|
||||
|
||||
mod brushes;
|
||||
mod dynamic;
|
||||
mod symbols;
|
||||
@@ -33,15 +36,16 @@ use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove,
|
||||
brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
|
||||
pub(crate) use dynamic::{edit_part, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{
|
||||
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
stored_natural_size,
|
||||
};
|
||||
use symbols::{
|
||||
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
|
||||
symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_instance_reset_transform, symbol_list, symbol_new, symbol_options,
|
||||
symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
};
|
||||
|
||||
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
|
||||
@@ -140,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
@@ -263,6 +267,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
symbol_instance_set_appearance
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.selectPart",
|
||||
"Select Symbol Instance Part",
|
||||
[],
|
||||
None,
|
||||
"{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke with a solid color or none, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom with a solid fill and stroke (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused) change that object's fill or stroke for this instance only; gradients and patterns are refused, and so are the commands that change the selected objects without ids (transparency.set, the gradient commands, object.group, edit.cut and edit.clear among them); edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}",
|
||||
has_doc,
|
||||
symbol_instance_select_part
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.reset",
|
||||
"Reset Symbol Instance",
|
||||
@@ -272,6 +285,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
symbol_instance_reset
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.resetTransform",
|
||||
"Reset Transformation",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} give the selected symbol instances (in groups too) their symbol's own scale, without rotation, shear or reflection, keeping the center of each one's bounding box in place, as one undo step; other objects, instances in perspective and instances already at their symbol's scale are left as they are, and no undo step is added when nothing changes; an id naming no object, or no symbol instance among the objects, is an error → {ids: the instances changed}",
|
||||
has_selection,
|
||||
symbol_instance_reset_transform
|
||||
),
|
||||
cmd!(
|
||||
"symbol.setCurrent",
|
||||
"Current Symbol",
|
||||
|
||||
@@ -61,6 +61,62 @@ fn dynamic_instance(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, Arc<No
|
||||
Ok((id, sym.art.clone()))
|
||||
}
|
||||
|
||||
/// The selected object of a dynamic symbol instance's art (Direct Selection): the instance and the
|
||||
/// object's path in the symbol's art.
|
||||
pub(crate) fn selected_part(s: &Session) -> Result<Option<(NodeId, Vec<u32>)>> {
|
||||
Ok(s.doc()?.selection.symbol_part.as_ref().map(|sp| (sp.instance, sp.path.clone())))
|
||||
}
|
||||
|
||||
/// Change instance `id`'s own appearance for the object at `path` of its art by `f`, as one undo
|
||||
/// step named `label`; nothing is recorded when the change leaves it as it was. Replies how many
|
||||
/// objects the instance changes.
|
||||
pub(crate) fn edit_part(s: &mut Session, id: NodeId, path: &[u32], label: &str, f: impl FnOnce(&mut SymbolOverride)) -> Result<usize> {
|
||||
let list = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.extras().symbol_overrides.clone();
|
||||
let old = list.iter().find(|o| o.path == path).cloned().unwrap_or_else(|| SymbolOverride { path: path.to_vec(), ..Default::default() });
|
||||
let mut new = old.clone();
|
||||
f(&mut new);
|
||||
if new == old {
|
||||
return Ok(list.len());
|
||||
}
|
||||
s.edit(label, |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut e = n.extras_mut();
|
||||
let list = &mut e.symbol_overrides;
|
||||
list.retain(|o| o.path != path);
|
||||
if !new.is_empty() {
|
||||
list.push(new);
|
||||
}
|
||||
Ok(list.len())
|
||||
})
|
||||
}
|
||||
|
||||
/// The refusal of anything but a solid color fill or stroke change while an object of a symbol
|
||||
/// instance's art is selected ([`selected_part`]), and of selecting any other object of the art.
|
||||
pub(crate) fn part_only() -> EngineError {
|
||||
EngineError::Other("Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change".into())
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_select_part(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.instance.selectPart";
|
||||
if p.get("id").is_none() {
|
||||
return Err(bad(C, "missing id"));
|
||||
}
|
||||
let (id, art) = dynamic_instance(s, p, C)?;
|
||||
let path = path_param(p, &art, C)?;
|
||||
// Direct Selection passes over hidden, locked and template objects, and over everything in a
|
||||
// group or layer that is: the instance in the document, and the object in the symbol's art.
|
||||
let editable = |n: &Node| n.visible && !n.locked && !n.is_template();
|
||||
if !s.doc()?.doc.is_editable(id) || !(0..=path.len()).all(|k| symbol_overrides::part(&art, &path[..k]).is_some_and(editable)) {
|
||||
return Err(bad(C, "the object is hidden or locked"));
|
||||
}
|
||||
if !symbol_overrides::part(&art, &path).is_some_and(symbol_overrides::takes_part_paint) {
|
||||
return Err(part_only());
|
||||
}
|
||||
let shown = json!(path);
|
||||
s.select(|_, sel| sel.set_symbol_part(id, path))?;
|
||||
Ok(json!({ "id": id.0, "path": shown }))
|
||||
}
|
||||
|
||||
/// The `path` param: child indices from the art's root, naming an object of `art`.
|
||||
fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> {
|
||||
let path: Option<Vec<u32>> =
|
||||
@@ -117,16 +173,7 @@ pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Resu
|
||||
let d = &s.doc()?.doc;
|
||||
let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned());
|
||||
let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?;
|
||||
let count = s.edit("Symbol Instance Appearance", |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut e = n.extras_mut();
|
||||
let list = &mut e.symbol_overrides;
|
||||
list.retain(|o| o.path != path);
|
||||
if !new.is_empty() {
|
||||
list.push(new);
|
||||
}
|
||||
Ok(list.len())
|
||||
})?;
|
||||
let count = edit_part(s, id, &path, "Symbol Instance Appearance", |o| *o = new)?;
|
||||
Ok(json!({ "id": id.0, "overrides": count }))
|
||||
}
|
||||
|
||||
|
||||
@@ -696,6 +696,62 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// How far a transform coefficient may be from Reset Transformation's for the instance to count as
|
||||
/// already reset.
|
||||
const RESET_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// The transform Reset Transformation gives instance `n` of the document of `boxes`: its symbol's
|
||||
/// own scale, without rotation, shear or reflection, with the center of its art's bounding box
|
||||
/// where it is. `None` when [`reset_transformation_changes`] is false for `n`.
|
||||
fn reset_transformation(boxes: &vectorcraft_doc::SymbolBoxes, n: &Node) -> Option<Affine> {
|
||||
let d = boxes.document();
|
||||
if !reset_transformation_changes(d, n) {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
|
||||
let scale = d.symbol_natural_xf(symbol);
|
||||
// The art's box in symbol space (the ±HALF square when the art cannot be measured): its
|
||||
// center keeps its place on the page.
|
||||
let art = boxes.art_bounds(symbol).unwrap_or_else(|| vectorcraft_geom::Rect::new(-HALF, -HALF, HALF, HALF));
|
||||
let center = xf.transform_rect_bbox(art).center();
|
||||
Some(Affine::translate(center - scale * art.center()) * scale)
|
||||
}
|
||||
|
||||
/// Does Reset Transformation change `n`? True for an instance of a symbol `d` holds, not in
|
||||
/// perspective, whose scale, rotation, shear or reflection differs from the symbol's own scale
|
||||
/// (its stored natural size, or the art unscaled when that size is not positive and finite).
|
||||
/// It does not measure the art.
|
||||
pub fn reset_transformation_changes(d: &Document, n: &Node) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return false };
|
||||
if n.extras().perspective.is_some() || !d.symbols.iter().any(|s| s.name == *symbol) {
|
||||
return false;
|
||||
}
|
||||
let natural = d.symbol_natural_xf(symbol).as_coeffs();
|
||||
xf.as_coeffs()[..4].iter().zip(&natural[..4]).any(|(a, b)| (a - b).abs() > RESET_TOLERANCE)
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_instances(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let boxes = d.symbol_boxes();
|
||||
let changes: Vec<(NodeId, Affine)> = ids.iter().filter_map(|id| Some((*id, reset_transformation(&boxes, d.node(*id)?)?))).collect();
|
||||
if !changes.is_empty() {
|
||||
s.edit("Reset Transformation", |d, _| {
|
||||
for (id, new) in &changes {
|
||||
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
*xf = *new;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
let changed: Vec<NodeId> = changes.iter().map(|(id, _)| *id).collect();
|
||||
Ok(json!({ "ids": ids_json(&changed) }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = resolve_symbol(&s.doc()?.doc, p, "symbol.setCurrent")?;
|
||||
set_unknown(s, CURRENT_SYMBOL, Some(json!(name)))?;
|
||||
@@ -832,6 +888,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0);
|
||||
let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0;
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
|
||||
crate::cmd::edit::refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let color = match color_param(p, "color", C)? {
|
||||
Some(c) => crate::cmd::paint::new_color(s, p, c),
|
||||
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make and Expand",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{…as imageTrace.make} same as imageTrace.make, then expand → {id, paths, anchors, colors}",
|
||||
"{…as imageTrace.make, byColor?: false (each color's paths in a group of their own, as imageTrace.expand)} same as imageTrace.make, then expand → {id, paths, anchors, colors}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, true)
|
||||
),
|
||||
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?, ids?: [id…] (instead of id)} keep only the traced paths (drop the source image) → {ids}",
|
||||
"{id?, ids?: [id…] (instead of id), byColor?: false (each color's paths in a group of their own, named by the swatch the color links to or as #rrggbb, gradient fills in one group named Gradients; the groups stack by their lowest path and keep their paths' order; a color whose paths overlap another color's from above and below gets a group for each part, so the art draws the same; refused for a trace made with autoGrouping and for a trace with a live Pathfinder effect)} keep only the traced paths (drop the source image) → {ids}",
|
||||
has_selection_or_ids,
|
||||
trace_expand
|
||||
),
|
||||
|
||||
@@ -4,10 +4,16 @@ use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::ImageObject;
|
||||
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point,
|
||||
Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point, Rect,
|
||||
Result, Session, StrokeLayer, TRACE_NAME, TraceView, Value, bad, fill_only, ids_json, json, root_ids, shape_node, str_param, switch_or, tr,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static BOX_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static CANDIDATE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
|
||||
fn is_trace_group(n: &Node) -> bool {
|
||||
@@ -16,6 +22,8 @@ fn is_trace_group(n: &Node) -> bool {
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
|
||||
|
||||
/// The `view` param ([`TraceView`] id), if given.
|
||||
fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
@@ -368,6 +376,156 @@ fn grouped(d: &mut Document, nodes: Vec<Node>, parents: &[Option<usize>]) -> Vec
|
||||
roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect()
|
||||
}
|
||||
|
||||
/// The `byColor` param of an Expand (false when not given).
|
||||
fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
|
||||
match p.get("byColor").filter(|v| !v.is_null()) {
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "byColor must be true or false")),
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand by color: an expanded trace's `items` (bottom-most first) in a group for each paint, a
|
||||
/// stroked line counted by its stroke. A solid color's group is named by the swatch it links to (a
|
||||
/// tint with its percentage) or as `#rrggbb`, and gradient fills share one group, "Gradients". The
|
||||
/// groups stack in the order of the lowest item in each, and each keeps its items' order. When the
|
||||
/// paths meet, an item joins its paint's last group only if no item of a later group meets it
|
||||
/// (by the boxes of everything they paint, effects included, within one point); otherwise it
|
||||
/// starts another group of that paint, which keeps the stacking order of those items. Items
|
||||
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
|
||||
/// their edge pixels may change. A group among `items` (Auto Grouping) is refused.
|
||||
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
use vectorcraft_color::tint_percent;
|
||||
// Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a
|
||||
// gradient, or another paint (its label). The name is apart from it: a swatch may be named as
|
||||
// a color's `#rrggbb` or as "Gradients".
|
||||
type PaintKey = (u8, String, u32);
|
||||
struct Run {
|
||||
name: String,
|
||||
members: Vec<Arc<Node>>,
|
||||
}
|
||||
// Boxes closer than a point count as overlapping: their antialiased edges can share pixels.
|
||||
let meet = |a: &Rect, b: &Rect| {
|
||||
#[cfg(test)]
|
||||
BOX_TESTS.with(|n| n.set(n.get() + 1));
|
||||
let b = b.inflate(1.0, 1.0);
|
||||
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
|
||||
};
|
||||
// Choose a cell size from the painted extent and path count. A box over more than eight cells
|
||||
// across but at most eight down (a stripe) is indexed by its rows, one the other way round by
|
||||
// its columns, and one over more than eight both ways stays in a separate list, keeping the
|
||||
// index bounded even when a path covers most of the document.
|
||||
let items: Vec<_> = items
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let bounds = vectorcraft_render::painted_bounds(d, &item);
|
||||
(item, bounds)
|
||||
})
|
||||
.collect();
|
||||
let extent = items.iter().filter_map(|(_, b)| *b).reduce(|a, b| a.union(b));
|
||||
let cell_size = extent.map_or(1.0, |r| ((r.x1 - r.x0).abs() * (r.y1 - r.y0).abs() / items.len().max(1) as f64).sqrt().max(1.0));
|
||||
// The first and last column and row of the cells `r` covers; `None` when it isn't finite.
|
||||
let span = |r: Rect| -> Option<(i64, i64, i64, i64)> {
|
||||
let coord = |v: f64| (v / cell_size).floor() as i64;
|
||||
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then(|| (coord(r.x0), coord(r.y0), coord(r.x1), coord(r.y1)))
|
||||
};
|
||||
let count = |first: i64, last: i64| i128::from(last) - i128::from(first) + 1;
|
||||
// A box over more cells than this is checked against every box.
|
||||
const MAX_CELLS: i128 = 1024;
|
||||
let mut groups: Vec<Run> = vec![];
|
||||
let mut latest: HashMap<PaintKey, usize> = HashMap::new();
|
||||
// An item can join an earlier group, so insertion order is not group-index order. Index
|
||||
// boxes by group to skip older groups without scanning their entries.
|
||||
let mut spatial: HashMap<(i64, i64), BTreeMap<usize, Vec<Rect>>> = HashMap::new();
|
||||
let mut rows: HashMap<i64, BTreeMap<usize, Vec<Rect>>> = HashMap::new();
|
||||
let mut columns: HashMap<i64, BTreeMap<usize, Vec<Rect>>> = HashMap::new();
|
||||
let mut large: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
let mut all_boxes: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
for (item, bounds) in items {
|
||||
if matches!(item.kind, NodeKind::Group { .. }) {
|
||||
return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
let paint = match item.appearance.fill_paint() {
|
||||
Paint::None => item.appearance.stroke_paint(),
|
||||
fill => fill,
|
||||
};
|
||||
let (key, name) = match &paint {
|
||||
Paint::Solid { swatch: Some(n), tint, .. } => {
|
||||
let percent = tint_percent(*tint);
|
||||
let name = if *tint < 1.0 { format!("{n} {percent}%") } else { n.clone() };
|
||||
((1, n.clone(), tint.to_bits()), name)
|
||||
}
|
||||
Paint::Solid { color, .. } => ((0, color.to_hex(), 0), color.to_hex()),
|
||||
Paint::Gradient(_) => ((2, String::new(), 0), "Gradients".to_string()),
|
||||
other => ((3, other.label(), 0), other.label()),
|
||||
};
|
||||
// Joining an earlier group moves the item under every later group's items.
|
||||
let hidden_by_later = |at: usize| {
|
||||
bounds.is_some_and(|b| {
|
||||
let overlaps_later = |boxes: &BTreeMap<usize, Vec<Rect>>| {
|
||||
boxes.range((Excluded(at), Unbounded)).rev().any(|(_, group_boxes)| {
|
||||
group_boxes.iter().rev().any(|box_bounds| {
|
||||
#[cfg(test)]
|
||||
CANDIDATE_VISITS.with(|n| n.set(n.get() + 1));
|
||||
meet(box_bounds, &b)
|
||||
})
|
||||
})
|
||||
};
|
||||
match span(b) {
|
||||
Some((x0, y0, x1, y1)) if count(x0, x1) * count(y0, y1) <= MAX_CELLS => {
|
||||
(y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))).filter_map(|c| spatial.get(&c)).any(overlaps_later)
|
||||
|| (y0..=y1).filter_map(|y| rows.get(&y)).any(overlaps_later)
|
||||
|| (x0..=x1).filter_map(|x| columns.get(&x)).any(overlaps_later)
|
||||
|| overlaps_later(&large)
|
||||
}
|
||||
_ => overlaps_later(&all_boxes),
|
||||
}
|
||||
})
|
||||
};
|
||||
let at = latest.get(&key).copied().filter(|&at| !hidden_by_later(at));
|
||||
let mut started = Run { name, members: vec![] };
|
||||
let joins = at.and_then(|at| groups.get_mut(at));
|
||||
let new = joins.is_none();
|
||||
let g = joins.unwrap_or(&mut started);
|
||||
g.members.push(item);
|
||||
if new {
|
||||
groups.push(started);
|
||||
latest.insert(key, groups.len() - 1);
|
||||
}
|
||||
if let Some(b) = bounds {
|
||||
let index = if new { groups.len() - 1 } else { at.unwrap_or_default() };
|
||||
all_boxes.entry(index).or_default().push(b);
|
||||
match span(b.inflate(1.0, 1.0)) {
|
||||
Some((x0, y0, x1, y1)) if count(x0, x1) <= 8 && count(y0, y1) <= 8 => {
|
||||
for place in (y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))) {
|
||||
spatial.entry(place).or_default().entry(index).or_default().push(b);
|
||||
}
|
||||
}
|
||||
Some((_, y0, _, y1)) if count(y0, y1) <= 8 => {
|
||||
for y in y0..=y1 {
|
||||
rows.entry(y).or_default().entry(index).or_default().push(b);
|
||||
}
|
||||
}
|
||||
Some((x0, _, x1, _)) if count(x0, x1) <= 8 => {
|
||||
for x in x0..=x1 {
|
||||
columns.entry(x).or_default().entry(index).or_default().push(b);
|
||||
}
|
||||
}
|
||||
_ => large.entry(index).or_default().push(b),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(groups
|
||||
.into_iter()
|
||||
.map(|run| {
|
||||
let mut g = Node::group(d.alloc_id(), run.members);
|
||||
g.name = Some(run.name);
|
||||
Arc::new(g)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
|
||||
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
|
||||
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
|
||||
@@ -398,6 +556,10 @@ struct Prepared {
|
||||
fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let mut params = trace_params(s, c, p)?;
|
||||
let view = view_param(c, p)?;
|
||||
let by_color = c == "imageTrace.makeAndExpand" && by_color_param(c, p)?;
|
||||
if by_color && params.auto_grouping {
|
||||
return Err(bad(c, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// The preset's name if the parameters are exactly that preset's or its enhanced version's (a
|
||||
// saved preset's under its saved name), else "Custom".
|
||||
@@ -428,6 +590,9 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))?
|
||||
};
|
||||
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
|
||||
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
let blob = s.doc()?.doc.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?;
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
@@ -533,6 +698,7 @@ impl TraceRun {
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
|
||||
let group_by_color = expand && by_color_param(c, p)?;
|
||||
// A saved preset's settings join the journal entry, so a replay traces as this run did after
|
||||
// the preset is changed, renamed or deleted.
|
||||
let named = str_param(p, "preset").unwrap_or("Default");
|
||||
@@ -608,6 +774,9 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
traced.push(n);
|
||||
}
|
||||
children.extend(grouped(d, traced, &res.parents));
|
||||
if group_by_color {
|
||||
children = color_groups(c, d, children)?;
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
@@ -706,7 +875,20 @@ pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.expand";
|
||||
let by_color = by_color_param(C, p)?;
|
||||
let targets = trace_targets(s, p)?;
|
||||
if by_color {
|
||||
// A trace made with Auto Grouping is refused even when none of its paths were grouped.
|
||||
let d = &s.doc()?.doc;
|
||||
let grouped = |n: &Node| n.extras().trace.as_deref().and_then(|t| t.pointer("/params/autoGrouping")).and_then(Value::as_bool) == Some(true);
|
||||
if targets.iter().any(|g| d.node(*g).is_some_and(grouped)) {
|
||||
return Err(bad(C, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
if targets.iter().any(|g| d.node(*g).is_some_and(vectorcraft_render::effects::has_pathfinder)) {
|
||||
return Err(bad(C, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
}
|
||||
s.edit("Expand Image Trace", |d, sel| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
@@ -715,6 +897,15 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| !matches!(c.kind, NodeKind::Image(_)));
|
||||
}
|
||||
if by_color {
|
||||
let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default();
|
||||
// The paths may have been moved or reshaped since the trace was made, so any trace's
|
||||
// paths are taken to overlap.
|
||||
let groups = color_groups(C, d, items)?;
|
||||
if let Some(ch) = d.node_mut(*g).and_then(Node::children_mut) {
|
||||
*ch = groups;
|
||||
}
|
||||
}
|
||||
}
|
||||
sel.set(targets.iter().copied());
|
||||
Ok(())
|
||||
@@ -722,6 +913,160 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&targets) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod color_group_tests {
|
||||
use super::*;
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
|
||||
fn area(d: &mut Document, x0: f64, y0: f64, x1: f64, y1: f64, color: Color) -> Arc<Node> {
|
||||
let path = PathData::single(SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true));
|
||||
Arc::new(Node::path(d.alloc_id(), path, fill_only(Paint::solid(color))))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abutting_color_groups_preserve_order_at_shared_edges() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let a = Color::rgb(1.0, 0.0, 0.0);
|
||||
let b = Color::rgb(0.0, 0.0, 1.0);
|
||||
let items = vec![area(&mut d, 0.0, 0.0, 20.0, 20.0, a), area(&mut d, 20.0, 0.0, 40.0, 20.0, b), area(&mut d, 40.0, 0.0, 60.0, 20.0, a)];
|
||||
let original: Vec<_> = items.iter().map(|n| n.id).collect();
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let actual: Vec<_> = groups.iter().flat_map(|g| g.children().unwrap().iter().map(|n| n.id)).collect();
|
||||
assert_eq!(actual, original, "shared-edge paths changed stacking order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dense_color_groups_use_bounded_box_tests() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let a = Color::rgb(1.0, 0.0, 0.0);
|
||||
let b = Color::rgb(0.0, 0.0, 1.0);
|
||||
let items = (0..4000)
|
||||
.map(|i| {
|
||||
if i % 2 == 0 {
|
||||
let x = 100.0 + (i % 40) as f64 * 0.01;
|
||||
area(&mut d, x, 100.0, x + 0.1, 100.1, a)
|
||||
} else {
|
||||
let x = if i % 4 == 1 { 0.0 } else { 198.0 };
|
||||
area(&mut d, x, x, x + 2.0, x + 2.0, b)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
BOX_TESTS.with(|n| n.set(0));
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let tests = BOX_TESTS.with(std::cell::Cell::get);
|
||||
assert_eq!(groups.iter().map(|g| g.children().map_or(0, Vec::len)).sum::<usize>(), 4000);
|
||||
assert!(tests < 4000 * 32, "{tests} box tests for 4000 paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_alternating_colors_visit_bounded_candidates() {
|
||||
const COUNT: usize = 3000;
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)];
|
||||
let items = (0..COUNT).map(|i| area(&mut d, 10.0, 10.0, 20.0, 20.0, colors[i % 2])).collect();
|
||||
CANDIDATE_VISITS.with(|n| n.set(0));
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let visits = CANDIDATE_VISITS.with(std::cell::Cell::get);
|
||||
assert_eq!(groups.len(), COUNT);
|
||||
assert!(visits < COUNT * 16, "{visits} candidate visits for {COUNT} paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_stripes_of_alternating_colors_visit_bounded_candidates() {
|
||||
const COUNT: usize = 2000;
|
||||
let mut d = Document::new(1000.0, 4000.0);
|
||||
let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)];
|
||||
for tall in [false, true] {
|
||||
let items = (0..COUNT)
|
||||
.map(|i| {
|
||||
let at = i as f64 * 2.0;
|
||||
if tall { area(&mut d, at, 0.0, at + 0.5, 1000.0, colors[i % 2]) } else { area(&mut d, 0.0, at, 1000.0, at + 0.5, colors[i % 2]) }
|
||||
})
|
||||
.collect();
|
||||
CANDIDATE_VISITS.with(|n| n.set(0));
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let visits = CANDIDATE_VISITS.with(std::cell::Cell::get);
|
||||
assert_eq!(groups.len(), 2, "tall {tall}");
|
||||
assert!(visits < COUNT * 32, "tall {tall}: {visits} candidate visits for {COUNT} stripes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spatial_color_groups_match_simple_scan() {
|
||||
let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)];
|
||||
for layout in 0..6 {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let items: Vec<_> = (0..90)
|
||||
.map(|i| {
|
||||
let x = match layout {
|
||||
0 => i as f64 * 2.0,
|
||||
1 => (i % 10) as f64 * 5.0,
|
||||
2 => (i % 7) as f64 * 3.0,
|
||||
3 => (i % 13) as f64 * 9.0,
|
||||
4 => (i % 4) as f64 * 10.0,
|
||||
_ => i as f64 * 1.5,
|
||||
};
|
||||
let y = match layout {
|
||||
0 => 0.0,
|
||||
1 => (i / 10) as f64 * 5.0,
|
||||
2 => (i / 7) as f64 * 3.0,
|
||||
3 => (i / 13) as f64 * 9.0,
|
||||
4 => i as f64 * 1.5,
|
||||
_ => (i % 4) as f64 * 10.0,
|
||||
};
|
||||
// Layouts 4 and 5: wide and tall stripes, some meeting their neighbors.
|
||||
let (w, h) = match layout {
|
||||
4 => (150.0, 1.0),
|
||||
5 => (1.0, 150.0),
|
||||
_ => (3.0, 3.0),
|
||||
};
|
||||
area(&mut d, x, y, x + w, y + h, colors[i % 3])
|
||||
})
|
||||
.collect();
|
||||
let mut expected: Vec<(String, Vec<(NodeId, Rect)>)> = vec![];
|
||||
for item in &items {
|
||||
let key = item.appearance.fill_paint().color().unwrap().to_hex();
|
||||
let bounds = vectorcraft_render::painted_bounds(&d, item).unwrap();
|
||||
let previous = expected.iter().rposition(|(k, _)| *k == key);
|
||||
let can_join = previous.filter(|&at| {
|
||||
!expected.iter().skip(at + 1).any(|(_, boxes)| {
|
||||
boxes.iter().any(|(_, m)| {
|
||||
let b = bounds.inflate(1.0, 1.0);
|
||||
m.x0 < b.x1 && b.x0 < m.x1 && m.y0 < b.y1 && b.y0 < m.y1
|
||||
})
|
||||
})
|
||||
});
|
||||
match can_join.and_then(|at| expected.get_mut(at)) {
|
||||
Some((_, members)) => members.push((item.id, bounds)),
|
||||
None => expected.push((key, vec![(item.id, bounds)])),
|
||||
}
|
||||
}
|
||||
let actual = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let actual: Vec<Vec<_>> = actual.iter().map(|g| g.children().unwrap().iter().map(|n| n.id).collect()).collect();
|
||||
let expected: Vec<Vec<_>> = expected.into_iter().map(|(_, members)| members.into_iter().map(|(id, _)| id).collect()).collect();
|
||||
assert_eq!(actual, expected, "layout {layout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_abutting_gradient_stays_above_the_solid_area_it_borders() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops.clone()))));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let mut area = |x0: f64, x1: f64, paint: Paint| {
|
||||
let path =
|
||||
PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 60.0), Point::new(x0, 60.0)], true));
|
||||
Arc::new(Node::path(d.alloc_id(), path, fill_only(paint)))
|
||||
};
|
||||
// A gradient, a solid area beside it and a second gradient beside that, bottom to top.
|
||||
let items = vec![area(0.0, 50.0, ramp()), area(50.0, 80.0, Paint::solid(Color::rgb(0.2, 0.6, 0.2))), area(80.0, 100.0, ramp())];
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let names: Vec<_> = groups.iter().map(|g| g.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Gradients", "#339933", "Gradients"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, trace_warnings};
|
||||
|
||||
@@ -241,9 +241,29 @@ pub(super) struct Used {
|
||||
impl Used {
|
||||
fn of<'a>(defs: &Defs<'a>, nodes: impl IntoIterator<Item = &'a Node>) -> Self {
|
||||
let mut used = Used::default();
|
||||
let mut todo: Vec<Source<'a>> = nodes.into_iter().map(Source::Node).collect();
|
||||
used.follow(defs, nodes.into_iter().map(Source::Node).collect());
|
||||
used
|
||||
}
|
||||
|
||||
/// Every character style of `defs` (with `chars`) and every paragraph style (with `paras`), and
|
||||
/// the resources they use, styles of the other kind included.
|
||||
fn of_text_styles(defs: &Defs<'_>, chars: bool, paras: bool) -> Self {
|
||||
let mut used = Used::default();
|
||||
let mut todo = vec![];
|
||||
for s in defs.char_styles.iter().filter(|_| chars) {
|
||||
used.note(defs, Ref::Name(Res::CharStyle, &s.name), &mut todo);
|
||||
}
|
||||
for s in defs.para_styles.iter().filter(|_| paras) {
|
||||
used.note(defs, Ref::Name(Res::ParaStyle, &s.name), &mut todo);
|
||||
}
|
||||
used.follow(defs, todo);
|
||||
used
|
||||
}
|
||||
|
||||
/// Note the references of `todo`'s sources and of the definitions they lead to.
|
||||
fn follow<'a>(&mut self, defs: &Defs<'a>, mut todo: Vec<Source<'a>>) {
|
||||
while let Some(src) = todo.pop() {
|
||||
let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo);
|
||||
let mut found = |r: Ref<'_>| self.note(defs, r, &mut todo);
|
||||
match src {
|
||||
Source::Node(n) => node_refs(n, &mut found),
|
||||
Source::Appearance(a) => appearance_refs(a, &mut found),
|
||||
@@ -251,7 +271,6 @@ impl Used {
|
||||
Source::Paint(p) => paint_refs(p, &mut found),
|
||||
}
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
/// Note `r`; a definition seen for the first time joins `todo`.
|
||||
@@ -505,7 +524,7 @@ impl SwatchChoices {
|
||||
}
|
||||
|
||||
/// How pasted art is relinked to the document's resources.
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Relink {
|
||||
renames: BTreeMap<Res, BTreeMap<String, String>>,
|
||||
/// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped.
|
||||
@@ -665,6 +684,227 @@ impl SymbolOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or
|
||||
/// brush (placed with the others only when they are placed in use order) to place
|
||||
/// ([`Clipboard::import_used`]).
|
||||
#[derive(Clone, Copy)]
|
||||
enum Def<'c> {
|
||||
Style(Res, &'c TextStyleDef),
|
||||
Symbol(&'c Symbol, Option<&'c SymbolOptions>),
|
||||
Pattern(&'c PatternDef),
|
||||
Brush(&'c Brush),
|
||||
}
|
||||
|
||||
impl<'c> Def<'c> {
|
||||
fn key(&self) -> (Res, &'c str) {
|
||||
match self {
|
||||
Def::Style(r, s) => (*r, &s.name),
|
||||
Def::Symbol(s, _) => (Res::Symbol, &s.name),
|
||||
Def::Pattern(p) => (Res::Pattern, &p.name),
|
||||
Def::Brush(b) => (Res::Brush, &b.name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `f` with each resource it refers to by name.
|
||||
fn each_use(&self, f: &mut dyn FnMut(Res, &str)) {
|
||||
let mut g = |r: Ref<'_>| {
|
||||
if let Ref::Name(res, n) = r {
|
||||
f(res, n);
|
||||
}
|
||||
};
|
||||
match self {
|
||||
Def::Style(_, s) => attrs_refs(&s.attrs, &mut g),
|
||||
Def::Symbol(s, _) => node_refs(&s.art, &mut g),
|
||||
Def::Pattern(p) => p.art.iter().for_each(|a| node_refs(a, &mut g)),
|
||||
Def::Brush(b) => b.art().into_iter().for_each(|a| node_refs(a, &mut g)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is it the definition `d` has under `name`, once relinked by `r`? (`brushes`: the brush
|
||||
/// library of `d`.)
|
||||
fn same_in(&self, d: &Document, brushes: &Brushes<'_>, name: &str, r: &Relink) -> bool {
|
||||
match self {
|
||||
Def::Style(res, s) => {
|
||||
let theirs = if *res == Res::CharStyle { &d.char_styles } else { &d.para_styles };
|
||||
let mut attrs = s.attrs.clone();
|
||||
r.attrs(&mut attrs);
|
||||
theirs.iter().any(|x| x.name == name && x.attrs == attrs)
|
||||
}
|
||||
Def::Symbol(s, options) => d.symbols.iter().any(|x| {
|
||||
x.name == name
|
||||
&& options.is_none_or(|o| SymbolOptions::of(d, name) == *o)
|
||||
&& same_art(r, std::slice::from_ref(&x.art), std::slice::from_ref(&s.art))
|
||||
}),
|
||||
Def::Pattern(p) => {
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
d.pattern(name).is_some_and(|x| bare(x) == bare(p) && same_art(r, &x.art, &p.art))
|
||||
}
|
||||
Def::Brush(b) => brushes.get().iter().any(|x| x.name == name && same_brush(r, x, b)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of its kind in `d` (`brushes`: its brush library) that are its name or a numbered
|
||||
/// copy of it.
|
||||
fn names_in(&self, d: &Document, brushes: &Brushes<'_>) -> Vec<String> {
|
||||
let (res, name) = self.key();
|
||||
let names: Vec<String> = match res {
|
||||
Res::CharStyle => d.char_styles.iter().map(|s| s.name.clone()).collect(),
|
||||
Res::ParaStyle => d.para_styles.iter().map(|s| s.name.clone()).collect(),
|
||||
Res::Symbol => d.symbols.iter().map(|s| s.name.clone()).collect(),
|
||||
Res::Brush => brushes.get().iter().map(|b| b.name.clone()).collect(),
|
||||
_ => d.patterns.iter().map(|p| p.name.clone()).collect(),
|
||||
};
|
||||
names.into_iter().filter(|n| copy_of(name, n)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// `defs` in rounds: each round takes those that use none of the others left, in their order.
|
||||
/// → (those, the rest, which use each other in a loop or use one that does, in their order)
|
||||
fn use_order(defs: Vec<Def<'_>>) -> (Vec<Def<'_>>, Vec<Def<'_>>) {
|
||||
let uses = uses_of(&defs);
|
||||
// The round of each definition; `None` for one in a loop or one that uses such a definition.
|
||||
let mut round: Vec<Option<usize>> = vec![None; defs.len()];
|
||||
// A group outside a loop holds one definition, and comes after the groups it uses.
|
||||
for (group, looped) in components(&uses) {
|
||||
for v in group.into_iter().filter(|_| !looped) {
|
||||
let r = uses[v].iter().try_fold(0, |r, &w| round.get(w).copied().flatten().map(|k| r.max(k + 1)));
|
||||
round[v] = r;
|
||||
}
|
||||
}
|
||||
let mut ready: Vec<(usize, usize)> = round.iter().enumerate().filter_map(|(i, r)| r.map(|r| (r, i))).collect();
|
||||
ready.sort_unstable();
|
||||
let order = ready.into_iter().filter_map(|(_, i)| defs.get(i).copied()).collect();
|
||||
let rest = defs.iter().zip(&round).filter(|(_, r)| r.is_none()).map(|(def, _)| *def).collect();
|
||||
(order, rest)
|
||||
}
|
||||
|
||||
/// The positions in `defs` of the definitions each one uses, itself included.
|
||||
fn uses_of(defs: &[Def<'_>]) -> Vec<Vec<usize>> {
|
||||
let mut at: BTreeMap<(Res, &str), Vec<usize>> = BTreeMap::new();
|
||||
for (i, def) in defs.iter().enumerate() {
|
||||
at.entry(def.key()).or_default().push(i);
|
||||
}
|
||||
defs.iter()
|
||||
.map(|def| {
|
||||
let mut to = vec![];
|
||||
def.each_use(&mut |res, n| to.extend(at.get(&(res, n)).into_iter().flatten()));
|
||||
to.sort_unstable();
|
||||
to.dedup();
|
||||
to
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `rest` ([`use_order`]'s definitions that use each other in a loop or use one that does) split
|
||||
/// into its loops and the definitions outside a loop, each group after the groups it uses:
|
||||
/// (positions in `rest`, in their order; true for a loop, definitions that use each other or one
|
||||
/// that uses itself).
|
||||
fn loop_groups(rest: &[Def<'_>]) -> Vec<(Vec<usize>, bool)> {
|
||||
components(&uses_of(rest))
|
||||
}
|
||||
|
||||
/// The strongly connected components of the graph `uses` (each node's successors), each after
|
||||
/// those it reaches: (nodes, in their order; true for a loop, two or more nodes or one that uses
|
||||
/// itself).
|
||||
fn components(uses: &[Vec<usize>]) -> Vec<(Vec<usize>, bool)> {
|
||||
// Tarjan's algorithm, with an explicit stack of calls.
|
||||
const NONE: usize = usize::MAX;
|
||||
let (mut index, mut low, mut on) = (vec![NONE; uses.len()], vec![0; uses.len()], vec![false; uses.len()]);
|
||||
let (mut stack, mut next, mut groups) = (vec![], 0, vec![]);
|
||||
for root in 0..uses.len() {
|
||||
if index[root] != NONE {
|
||||
continue;
|
||||
}
|
||||
let mut calls: Vec<(usize, usize)> = vec![(root, 0)];
|
||||
(index[root], low[root], on[root]) = (next, next, true);
|
||||
next += 1;
|
||||
stack.push(root);
|
||||
while let Some(&(v, k)) = calls.last() {
|
||||
if let Some(&w) = uses[v].get(k) {
|
||||
if let Some(top) = calls.last_mut() {
|
||||
top.1 += 1;
|
||||
}
|
||||
if index[w] == NONE {
|
||||
(index[w], low[w], on[w]) = (next, next, true);
|
||||
next += 1;
|
||||
stack.push(w);
|
||||
calls.push((w, 0));
|
||||
} else if on[w] {
|
||||
low[v] = low[v].min(index[w]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
calls.pop();
|
||||
if let Some(&(u, _)) = calls.last() {
|
||||
low[u] = low[u].min(low[v]);
|
||||
}
|
||||
if low[v] == index[v] {
|
||||
let mut group = vec![];
|
||||
while let Some(w) = stack.pop() {
|
||||
on[w] = false;
|
||||
group.push(w);
|
||||
if w == v {
|
||||
break;
|
||||
}
|
||||
}
|
||||
group.sort_unstable();
|
||||
let looped = group.len() > 1 || uses[v].contains(&v);
|
||||
groups.push((group, looped));
|
||||
}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// The names in `d` that `looped` (a loop of definitions that use each other, [`loop_groups`])
|
||||
/// all have at once, each the same once relinked by `r` with those names: each one's name or a
|
||||
/// numbered copy of it. The names are picked one definition at a time, in order, and each
|
||||
/// definition is compared as soon as the names of those it uses are picked, so a pick that does
|
||||
/// not fit is dropped with every combination that follows from it; at most 65,536 comparisons are
|
||||
/// made. `None` when no combination fits, or none was found within that many comparisons. The brush
|
||||
/// library of `d` is read once, the first time a brush is compared.
|
||||
fn names_of_loop(d: &Document, looped: &[Def<'_>], r: &Relink) -> Option<Vec<String>> {
|
||||
let library = OnceCell::new();
|
||||
let brushes = Brushes::Lazy(d, &library);
|
||||
let names: Vec<Vec<String>> = looped.iter().map(|def| def.names_in(d, &brushes)).collect();
|
||||
if names.is_empty() || names.iter().any(Vec::is_empty) {
|
||||
return None;
|
||||
}
|
||||
// The definitions compared once the name at each position is picked.
|
||||
let mut compare_at: Vec<Vec<usize>> = vec![vec![]; looped.len()];
|
||||
for (i, uses) in uses_of(looped).iter().enumerate() {
|
||||
compare_at[uses.iter().copied().fold(i, usize::max)].push(i);
|
||||
}
|
||||
let (mut pick, mut guess, mut budget, mut k) = (vec![0usize; looped.len()], r.clone(), 1usize << 16, 0);
|
||||
loop {
|
||||
let (res, own) = looped[k].key();
|
||||
guess.renames.entry(res).or_default().insert(own.to_string(), names[k][pick[k]].clone());
|
||||
let fits = compare_at[k].iter().all(|&i| {
|
||||
budget = budget.saturating_sub(1);
|
||||
looped[i].same_in(d, &brushes, &names[i][pick[i]], &guess)
|
||||
});
|
||||
if fits && k + 1 == looped.len() {
|
||||
return Some(names.iter().zip(&pick).map(|(l, &p)| l[p].clone()).collect());
|
||||
}
|
||||
if budget == 0 {
|
||||
return None;
|
||||
}
|
||||
if fits {
|
||||
k += 1;
|
||||
pick[k] = 0;
|
||||
continue;
|
||||
}
|
||||
// The next name at this position, or back to the position before.
|
||||
loop {
|
||||
pick[k] += 1;
|
||||
if pick[k] < names[k].len() {
|
||||
break;
|
||||
}
|
||||
k = k.checked_sub(1)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What pasting did to the document's resources (part of the paste result).
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Imported {
|
||||
@@ -704,6 +944,12 @@ impl Clipboard {
|
||||
pub(crate) fn gather(src: &Document, nodes: Vec<Node>) -> Self {
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of(&Defs::of(src, &library), &nodes);
|
||||
Self::with_used(src, &used, &library, nodes)
|
||||
}
|
||||
|
||||
/// `nodes` and the resources of `src` that `used` names (`library`: the brush library of `src`,
|
||||
/// read when a brush was used).
|
||||
fn with_used(src: &Document, used: &Used, library: &OnceCell<Vec<Brush>>, nodes: Vec<Node>) -> Self {
|
||||
let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::<Vec<_>>();
|
||||
// Read when a brush was used.
|
||||
let brushes = match (used.names.get(&Res::Brush), library.get()) {
|
||||
@@ -757,61 +1003,158 @@ impl Clipboard {
|
||||
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
|
||||
/// pasted copies relink to them.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported {
|
||||
let used = self.used();
|
||||
self.import_used(d, &self.used(), choices, same_doc, false)
|
||||
}
|
||||
|
||||
/// [`Self::import_into`] for the resources `used` names. The character and paragraph styles
|
||||
/// come before the symbols and patterns, whose art may set type in them; with `in_use_order`,
|
||||
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
|
||||
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
|
||||
/// of definitions that use each other is matched on its own ([`loop_groups`]).
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported {
|
||||
let mut out = Imported::default();
|
||||
self.import_images(d, &used, same_doc, &mut out);
|
||||
self.import_swatches(d, &used, choices, same_doc, &mut out);
|
||||
self.import_images(d, used, same_doc, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
|
||||
// they may brush; the others once those are in.
|
||||
let mut added_brushes: HashSet<String> = self.import_brushes(d, &used, same_doc, false, &mut out).into_iter().collect();
|
||||
// Character and paragraph styles (their colours relinked first).
|
||||
for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] {
|
||||
for def in mine.iter().filter(|s| used.has(r, &s.name)) {
|
||||
let mut s = def.clone();
|
||||
// they may brush; the others once those are in. With `in_use_order`, the brushes are
|
||||
// placed in use order with the others.
|
||||
let mut added_brushes: HashSet<String> =
|
||||
if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() };
|
||||
let mut defs: Vec<Def<'_>> = vec![];
|
||||
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
|
||||
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
|
||||
}
|
||||
defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name))));
|
||||
defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern));
|
||||
if in_use_order {
|
||||
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
|
||||
}
|
||||
// Groups to place in order; true for a loop of definitions that use each other.
|
||||
let groups: Vec<(Vec<Def<'_>>, bool)> = if in_use_order {
|
||||
let (order, rest) = use_order(defs);
|
||||
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
|
||||
std::iter::once((order, false)).chain(loops).collect()
|
||||
} else {
|
||||
vec![(defs, false)]
|
||||
};
|
||||
// Styles (their colors relinked first), symbols and patterns (compared once relinked,
|
||||
// symbols with their options too). The symbols and patterns added are relinked at the end,
|
||||
// when every new name and graphic style id is known; with `in_use_order`, so are the
|
||||
// styles added, which a loop of uses may place before a pattern they paint with.
|
||||
let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]);
|
||||
// Each definition, whether it is in a loop, and the loop it starts.
|
||||
let steps = groups
|
||||
.iter()
|
||||
.flat_map(|(group, looped)| group.iter().enumerate().map(move |(i, def)| (*def, *looped, (*looped && i == 0).then_some(group))));
|
||||
// In a loop the document does not have all at once, every definition uses one that is
|
||||
// added under a free name, so each one is added too.
|
||||
let mut fresh = false;
|
||||
// The names in the document of the loop being placed, when it has them all at once.
|
||||
let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new();
|
||||
// The document's brush library, read the first time a brush is placed in use order and
|
||||
// stored again after each brush added; nothing else in the loop changes it.
|
||||
let mut library: Option<Vec<Brush>> = None;
|
||||
for (def, looped, starts) in steps {
|
||||
fresh &= looped;
|
||||
if !looped {
|
||||
matched.clear();
|
||||
}
|
||||
// A loop of uses that the document has all at once is known under those names before
|
||||
// its definitions are compared.
|
||||
if let Some(group) = starts {
|
||||
matched.clear();
|
||||
match names_of_loop(d, group, &out.relink) {
|
||||
Some(names) => {
|
||||
for (def, name) in group.iter().zip(names) {
|
||||
let (res, own) = def.key();
|
||||
if own != name {
|
||||
out.relink.renames.entry(res).or_default().insert(own.to_string(), name.clone());
|
||||
}
|
||||
matched.insert((res, own.to_string()), name);
|
||||
}
|
||||
fresh = false;
|
||||
}
|
||||
None => fresh = true,
|
||||
}
|
||||
}
|
||||
// A definition of such a loop is the document's under the name found for it.
|
||||
let (res, own) = def.key();
|
||||
if let Some(name) = matched.get(&(res, own.to_string())) {
|
||||
let p = if name == own { Placed::Existing } else { Placed::Reused(name.clone()) };
|
||||
out.placed(res, own, &p);
|
||||
continue;
|
||||
}
|
||||
match def {
|
||||
Def::Style(r, def) => {
|
||||
let mut s = def.clone();
|
||||
out.relink.attrs(&mut s.attrs);
|
||||
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
|
||||
let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b);
|
||||
if in_use_order && let Some(name) = p.new_name(&def.name) {
|
||||
added_styles.push((r, name, def));
|
||||
}
|
||||
out.placed(r, &def.name, &p);
|
||||
}
|
||||
Def::Symbol(def, options) => {
|
||||
let theirs: HashMap<String, SymbolOptions> = match options {
|
||||
Some(_) => d
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|s| copy_of(&def.name, &s.name))
|
||||
.map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name)))
|
||||
.collect(),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let r = &out.relink;
|
||||
let p = place(&mut d.symbols, def, same_doc, |a, b| {
|
||||
!fresh
|
||||
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
|
||||
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
});
|
||||
if let Some(name) = p.new_name(&def.name) {
|
||||
if let Some(o) = options {
|
||||
o.give(d, &name);
|
||||
}
|
||||
added_symbols.insert(name);
|
||||
}
|
||||
out.placed(Res::Symbol, &def.name, &p);
|
||||
}
|
||||
Def::Pattern(def) => {
|
||||
// Tile options alike, and the art once relinked.
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
|
||||
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
|
||||
// Its swatch comes along under the same name.
|
||||
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
|
||||
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
|
||||
Placed::added(&def.name, name)
|
||||
});
|
||||
added_patterns.extend(p.new_name(&def.name));
|
||||
out.placed(Res::Pattern, &def.name, &p);
|
||||
}
|
||||
Def::Brush(b) => {
|
||||
let lib = library.get_or_insert_with(|| vectorcraft_brush::library(d));
|
||||
let r = &out.relink;
|
||||
let p = place(lib, b, same_doc, |ours, theirs| !fresh && same_brush(r, ours, theirs));
|
||||
if let Some(name) = p.new_name(&b.name) {
|
||||
vectorcraft_brush::store(d, lib);
|
||||
added_brushes.insert(name);
|
||||
}
|
||||
out.placed(Res::Brush, &b.name, &p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !in_use_order {
|
||||
added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out));
|
||||
}
|
||||
self.import_graphic_styles(d, used, same_doc, &mut out);
|
||||
for (r, name, def) in added_styles {
|
||||
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
|
||||
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
|
||||
s.attrs = def.attrs.clone();
|
||||
out.relink.attrs(&mut s.attrs);
|
||||
let p = place(theirs, &s, same_doc, PartialEq::eq);
|
||||
out.placed(r, &def.name, &p);
|
||||
}
|
||||
}
|
||||
// Symbols and patterns, compared once relinked (symbols with their options too). Those
|
||||
// added are relinked at the end, when every new name and graphic style id is known.
|
||||
let mut added_symbols = HashSet::new();
|
||||
for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) {
|
||||
let options = self.symbol_options.get(&def.name);
|
||||
let theirs: HashMap<String, SymbolOptions> = match options {
|
||||
Some(_) => {
|
||||
d.symbols.iter().filter(|s| copy_of(&def.name, &s.name)).map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name))).collect()
|
||||
}
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let r = &out.relink;
|
||||
let p = place(&mut d.symbols, def, same_doc, |a, b| {
|
||||
options.is_none_or(|o| theirs.get(&a.name) == Some(o)) && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
});
|
||||
if let Some(name) = p.new_name(&def.name) {
|
||||
if let Some(o) = options {
|
||||
o.give(d, &name);
|
||||
}
|
||||
added_symbols.insert(name);
|
||||
}
|
||||
out.placed(Res::Symbol, &def.name, &p);
|
||||
}
|
||||
let mut added_patterns = HashSet::new();
|
||||
for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) {
|
||||
// Tile options alike, and the art once relinked.
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let same = |n: &str| d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
|
||||
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
|
||||
// Its swatch comes along under the same name.
|
||||
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
|
||||
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
|
||||
Placed::added(&def.name, name)
|
||||
});
|
||||
added_patterns.extend(p.new_name(&def.name));
|
||||
out.placed(Res::Pattern, &def.name, &p);
|
||||
}
|
||||
added_brushes.extend(self.import_brushes(d, &used, same_doc, true, &mut out));
|
||||
self.import_graphic_styles(d, &used, same_doc, &mut out);
|
||||
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
|
||||
out.relink.node(Arc::make_mut(&mut s.art));
|
||||
}
|
||||
@@ -925,6 +1268,43 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a loaded text style is in the document ([`import_text_styles`]).
|
||||
pub(crate) struct LoadedStyle {
|
||||
/// A paragraph style (else a character style).
|
||||
pub para: bool,
|
||||
/// Its name in the document.
|
||||
pub name: String,
|
||||
/// It was added (else the document's own was the same).
|
||||
pub added: bool,
|
||||
}
|
||||
|
||||
/// Add every character style of `src` (with `chars`) and every paragraph style (with `paras`) to
|
||||
/// `d`, with the swatches, patterns and what their art uses (styles of the other kind included)
|
||||
/// that the styles' fill and stroke lead to, as Paste adds those of pasted type
|
||||
/// ([`Clipboard::import_into`]; a global or spot color whose name `d` gives another color is
|
||||
/// `d`'s). Each style, symbol and pattern is placed after those it uses, so that a style follows
|
||||
/// a pattern added under a free name and a pattern follows a style renamed on the way in. A style
|
||||
/// `d` has under its name, or a numbered copy of it ("Body 2"), that is the same once relinked is
|
||||
/// used; any other is added under a free name. → each style of `src` placed, in order, character
|
||||
/// styles first.
|
||||
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Vec<LoadedStyle> {
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true);
|
||||
let mut placed: Vec<LoadedStyle> = vec![];
|
||||
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
|
||||
for s in list {
|
||||
let name = out.relink.renamed(r, &s.name);
|
||||
let again = placed.iter().any(|p| p.para == para && p.name == name);
|
||||
let added = !again && !before[usize::from(para)].contains(&name);
|
||||
placed.push(LoadedStyle { para, name, added });
|
||||
}
|
||||
}
|
||||
placed
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
/// share one namespace).
|
||||
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
|
||||
|
||||
@@ -19,7 +19,7 @@ use vectorcraft_render::proof;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::EngineError;
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, color_value, has_doc, str_param, targets};
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param};
|
||||
|
||||
/// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated
|
||||
/// to `Document::color_profiles` on load).
|
||||
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
proof_setup
|
||||
),
|
||||
cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| {
|
||||
toggle_view(s, p, |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
|
||||
toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
|
||||
}),
|
||||
cmd!(
|
||||
query "view.overprintPreview",
|
||||
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some("Cmd+Alt+Shift+Y"),
|
||||
"{on?: bool (default: toggle)} → proof state",
|
||||
always,
|
||||
|s, p| toggle_view(s, p, |v, on| v.overprint = on.unwrap_or(!v.overprint))
|
||||
|s, p| toggle_view(s, p, "view.overprintPreview", |v, on| v.overprint = on.unwrap_or(!v.overprint))
|
||||
),
|
||||
cmd!(
|
||||
query "view.separationsPreview",
|
||||
@@ -143,12 +143,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
fn intent_param(p: &Value, cmd: &str) -> Result<Option<Intent>> {
|
||||
match str_param(p, "intent") {
|
||||
match text_param(p, "intent", cmd)? {
|
||||
None => Ok(None),
|
||||
Some(i) => Intent::parse(i).map(Some).ok_or_else(|| bad(cmd, format!("unknown intent `{i}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The true or false `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other
|
||||
/// value is an error, as [`switch_or`] reads it.
|
||||
fn on_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
|
||||
if p.get(key).is_none_or(Value::is_null) {
|
||||
return Ok(None);
|
||||
}
|
||||
switch_or(p, key, false, cmd).map(Some)
|
||||
}
|
||||
|
||||
fn settings_json(st: &ColorSettings) -> Value {
|
||||
json!({
|
||||
"rgb": st.rgb,
|
||||
@@ -171,16 +180,16 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.colorSettings";
|
||||
let mut st = cms::active_settings();
|
||||
let before = st.clone();
|
||||
if let Some(v) = str_param(p, "rgb") {
|
||||
if let Some(v) = text_param(p, "rgb", C)? {
|
||||
st.rgb = cms::canonical_name(v).to_string();
|
||||
}
|
||||
if let Some(v) = str_param(p, "cmyk") {
|
||||
if let Some(v) = text_param(p, "cmyk", C)? {
|
||||
st.cmyk = cms::canonical_name(v).to_string();
|
||||
}
|
||||
if let Some(i) = intent_param(p, C)? {
|
||||
st.intent = i;
|
||||
}
|
||||
st.bpc = bool_or(p, "bpc", st.bpc);
|
||||
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
|
||||
if st != before {
|
||||
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
|
||||
touch_all(s);
|
||||
@@ -191,7 +200,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.loadProfile";
|
||||
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
let path = text_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
crate::file_access::check_read(path).map_err(EngineError::Other)?;
|
||||
let bytes = crate::store::read_capped(std::path::Path::new(path), crate::store::MAX_PROFILE_FILE).map_err(|e| bad(C, format!("{path}: {e}")))?;
|
||||
let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?;
|
||||
@@ -209,7 +218,7 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Forget a profile `color.loadProfile` loaded, and the copy that is kept of it.
|
||||
fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.removeProfile";
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?;
|
||||
let info = cms::profiles().into_iter().find(|i| i.name == name).ok_or_else(|| bad(C, format!("no profile named `{name}`")))?;
|
||||
if info.builtin {
|
||||
return Err(bad(C, format!("`{name}` is a built-in profile and stays")));
|
||||
@@ -289,7 +298,7 @@ pub enum Grays {
|
||||
impl Grays {
|
||||
/// The `grays` param of `cmd`: `"profile"` (default) or `"black"`.
|
||||
pub(crate) fn param(cmd: &str, p: &Value) -> Result<Self> {
|
||||
match str_param(p, "grays").map(str::to_ascii_lowercase).as_deref() {
|
||||
match text_param(p, "grays", cmd)?.map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("profile") => Ok(Grays::Profile),
|
||||
Some("black") => Ok(Grays::Black),
|
||||
Some(g) => Err(bad(cmd, format!("grays must be \"profile\" or \"black\", not `{g}`"))),
|
||||
@@ -302,18 +311,18 @@ impl Grays {
|
||||
/// colour through the colour settings.
|
||||
pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.documentColorMode";
|
||||
let mode = match str_param(p, "mode").map(str::to_ascii_lowercase).as_deref() {
|
||||
let mode = match p.get("mode").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("cmyk") => ColorMode::Cmyk,
|
||||
Some("rgb") => ColorMode::Rgb,
|
||||
_ => return Err(bad(C, "mode must be \"cmyk\" or \"rgb\"")),
|
||||
};
|
||||
let intent = intent_param(p, C)?;
|
||||
let grays = Grays::param(C, p)?;
|
||||
let convert = switch_or(p, "convert", true, C)?;
|
||||
// Choosing the mode the document already has (the checked menu item) is not an edit.
|
||||
if s.doc()?.doc.color_mode == mode {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let convert = bool_or(p, "convert", true);
|
||||
let mut changed = 0usize;
|
||||
s.edit("Document Color Mode", |d, _| {
|
||||
changed = set_color_mode(d, mode, convert, intent, grays);
|
||||
@@ -654,7 +663,7 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = cms::active();
|
||||
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
|
||||
let lab = c.lab(&col);
|
||||
let (model, vals) = match str_param(p, "to").unwrap_or("rgb") {
|
||||
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
|
||||
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
|
||||
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
|
||||
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
|
||||
@@ -674,7 +683,11 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn gamut_check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut cols: Vec<Color> = vec![];
|
||||
if let Some(a) = p.get("colors").and_then(Value::as_array) {
|
||||
let colors = p.get("colors").filter(|v| !v.is_null());
|
||||
if let Some(v) = colors.filter(|v| !v.is_array()) {
|
||||
return Err(bad("color.gamutCheck", format!("`colors` must be an array of colors, not {v}")));
|
||||
}
|
||||
if let Some(a) = colors.and_then(Value::as_array) {
|
||||
for v in a {
|
||||
cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?);
|
||||
}
|
||||
@@ -728,7 +741,7 @@ fn view_json(v: &proof::ProofView) -> Value {
|
||||
fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.proofSetup";
|
||||
let mut v = proof::view();
|
||||
if let Some(t) = str_param(p, "target") {
|
||||
if let Some(t) = text_param(p, "target", C)? {
|
||||
let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?;
|
||||
if let ProofTarget::Cmyk(name) = &t
|
||||
&& !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
|
||||
@@ -740,8 +753,8 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(i) = intent_param(p, C)? {
|
||||
v.setup.intent = i;
|
||||
}
|
||||
v.setup.simulate_paper = bool_or(p, "simulatePaper", v.setup.simulate_paper);
|
||||
if let Some(on) = p.get("proof").and_then(Value::as_bool) {
|
||||
v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?;
|
||||
if let Some(on) = on_param(p, "proof", C)? {
|
||||
v.proof_colors = on;
|
||||
}
|
||||
proof::set_view(v.clone());
|
||||
@@ -749,9 +762,10 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(view_json(&v))
|
||||
}
|
||||
|
||||
fn toggle_view(s: &mut Session, p: &Value, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
|
||||
fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
|
||||
let on = on_param(p, "on", cmd)?;
|
||||
let mut v = proof::view();
|
||||
f(&mut v, p.get("on").and_then(Value::as_bool));
|
||||
f(&mut v, on);
|
||||
proof::set_view(v.clone());
|
||||
touch_all(s);
|
||||
Ok(view_json(&v))
|
||||
@@ -779,16 +793,23 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|d| proof::plates(&d.doc).into_iter().map(|p| p.name).collect())
|
||||
.unwrap_or_else(|| cms::PROCESS_PLATES.iter().map(|s| s.to_string()).collect());
|
||||
let check = |n: &str| if all.iter().any(|a| a == n) { Ok(n.to_string()) } else { Err(bad(C, format!("unknown plate `{n}`"))) };
|
||||
if let Some(on) = p.get("on").and_then(Value::as_bool) {
|
||||
if let Some(on) = on_param(p, "on", C)? {
|
||||
v.separations = if on { Some(v.separations.take().unwrap_or_else(|| all.clone())) } else { None };
|
||||
}
|
||||
if let Some(a) = p.get("plates").and_then(Value::as_array) {
|
||||
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
|
||||
match p.get("plates") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Array(a)) if a.iter().all(Value::is_string) => {
|
||||
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
|
||||
}
|
||||
Some(_) => {
|
||||
let key = "plates";
|
||||
return Err(bad(C, format!("`{key}` must be an array of these names: {}", all.join(", "))));
|
||||
}
|
||||
}
|
||||
if let Some(n) = str_param(p, "only") {
|
||||
if let Some(n) = text_param(p, "only", C)? {
|
||||
v.separations = Some(vec![check(n)?]);
|
||||
}
|
||||
if let Some(n) = str_param(p, "toggle") {
|
||||
if let Some(n) = text_param(p, "toggle", C)? {
|
||||
let n = check(n)?;
|
||||
let vis = v.separations.get_or_insert_with(|| all.clone());
|
||||
if let Some(i) = vis.iter().position(|x| *x == n) {
|
||||
@@ -804,8 +825,8 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.setSpot";
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string();
|
||||
let spot = bool_or(p, "spot", true);
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?.to_string();
|
||||
let spot = switch_or(p, "spot", true, C)?;
|
||||
let sw = s.doc()?.doc.swatch(&name).ok_or_else(|| bad(C, format!("no swatch `{name}`")))?;
|
||||
if !matches!(sw.paint, Paint::Solid { .. }) {
|
||||
return Err(bad(C, "only solid-colour swatches can be spot colours"));
|
||||
|
||||
@@ -13,7 +13,7 @@ use vectorcraft_tools::distort::liquify::{Dabber, LiquifyParams, PathStroke, Sam
|
||||
use vectorcraft_tools::distort::perspective::{self as persp, PerspectiveGrid, Plane};
|
||||
use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project_node, stroke_owner, warp_from_rest, warp_node_with};
|
||||
|
||||
use super::edit::{duplicate_in, outermost, selected_roots};
|
||||
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, id_param,
|
||||
matrix_param, named_id, named_ids, number_or, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
@@ -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), 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",
|
||||
"{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, and moves every object on that plane, at any depth, by the same plane offset; Transform Again repeats it",
|
||||
has_doc,
|
||||
persp_move
|
||||
),
|
||||
@@ -730,8 +730,13 @@ fn puppet_warp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if pins.iter().chain(&moved).any(|q| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
return Err(bad(C, "pins must be finite"));
|
||||
}
|
||||
let ids =
|
||||
if rest { puppet_ids(p, || Ok(s.doc()?.selection.objects.clone()))? } else { outermost(&s.doc()?.doc, puppet_ids(p, || selected_roots(s))?) };
|
||||
// While an object of a dynamic symbol instance's art is selected, the selection is refused, as
|
||||
// `selected_roots` refuses it.
|
||||
let selected = || {
|
||||
refuse_symbol_part(s)?;
|
||||
Ok(s.doc()?.selection.objects.clone())
|
||||
};
|
||||
let ids = if rest { puppet_ids(p, selected)? } else { outermost(&s.doc()?.doc, puppet_ids(p, || selected_roots(s))?) };
|
||||
let expand = f64_or(p, "expand", 3.0).clamp(0.0, 1000.0);
|
||||
let angles: Vec<Option<f64>> = match p.get("angles") {
|
||||
None | Some(Value::Null) => vec![None; pins.len()],
|
||||
|
||||
@@ -285,7 +285,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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.
|
||||
// Shift: the constrained end point, read on the first object's plane and depth.
|
||||
let snap_to = if constrain && !perp {
|
||||
let doc = &s.doc()?.doc;
|
||||
let g = grid_of(doc);
|
||||
@@ -300,11 +300,20 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} 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| {
|
||||
// With Snap to Grid, every object on the first one's plane, at any depth, moves by the first
|
||||
// one's plane-space offset and its correction, so the objects keep their spacing on the plane.
|
||||
let fix = if perp {
|
||||
None
|
||||
} else {
|
||||
let doc = &s.doc()?.doc;
|
||||
crate::cmd::perspgrid::snap_fix(doc, &ids, p, (from, snap_to))
|
||||
.and_then(|(plane, depth, correction)| Some((plane, grid_of(doc).plane_delta(plane, depth, from, to)?, correction)))
|
||||
};
|
||||
let snapped = move |pl: Plane, raw: vectorcraft_geom::Vec2| {
|
||||
let raw = fix.filter(|f| f.0 == pl).map_or(raw, |f| f.1);
|
||||
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| {
|
||||
dv + fix.filter(|f| f.0 == pl).map_or(vectorcraft_geom::Vec2::ZERO, |f| {
|
||||
if !constrain {
|
||||
return f.2;
|
||||
}
|
||||
@@ -325,7 +334,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let to_depth = g.depth_at(pl, depth, from, to).ok_or_else(beyond_horizon)?;
|
||||
Ok((g.transform_map(pl, depth, Affine::IDENTITY, to_depth - depth).ok_or_else(beyond_horizon)?, to_depth))
|
||||
} else {
|
||||
let dv = snapped(pl, depth, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?);
|
||||
let dv = snapped(pl, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?);
|
||||
Ok((g.transform_map(pl, depth, Affine::translate(dv), 0.0).ok_or_else(beyond_horizon)?, depth))
|
||||
}
|
||||
};
|
||||
@@ -336,7 +345,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if perp {
|
||||
g.depth_at(pl, depth, from, to).is_some_and(|d| (d - depth).abs() <= 1e-9)
|
||||
} else {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, depth, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9)
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9)
|
||||
}
|
||||
};
|
||||
let first_still = if copy { None } else { unmoved(s, &ids, still)? };
|
||||
@@ -350,9 +359,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let again = match perp {
|
||||
_ if first_still.is_some() => Some(json!({"matrix": matrix_json(Affine::IDENTITY), "copy": copy})),
|
||||
true => g.depth_at(pl, depth, from, to).map(|d| json!({"matrix": matrix_json(Affine::IDENTITY), "depth": d - depth, "copy": copy})),
|
||||
false => {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, depth, dv))), "copy": copy}))
|
||||
}
|
||||
false => g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, dv))), "copy": copy})),
|
||||
};
|
||||
if let Some(a) = again {
|
||||
record_again(s, a)?;
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -130,13 +130,15 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts, its image objects and the rows of its Repeat objects.
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
|
||||
/// rows of its objects filled or stroked with a pattern.
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
images: &[ImageRow],
|
||||
repeats: &[(String, String)],
|
||||
pattern_objects: &[(String, String)],
|
||||
category: Option<&str>,
|
||||
) -> Vec<Section> {
|
||||
let names = |k: &str| -> Vec<(String, String)> {
|
||||
@@ -180,7 +182,7 @@ fn sections(
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
"brushes" => names("brushNames"),
|
||||
"spotColors" => names("spotColors"),
|
||||
"patterns" => names("patternNames"),
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(),
|
||||
"symbols" => names("symbols"),
|
||||
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
|
||||
@@ -252,12 +254,67 @@ pub fn report(s: &mut Session, selection_only: bool) -> Result<String> {
|
||||
Ok(v["text"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
fn paint_kind(p: &Paint) -> Option<&'static str> {
|
||||
match p {
|
||||
Paint::Gradient(_) => Some("gradients"),
|
||||
Paint::Pattern { .. } => Some("patterns"),
|
||||
_ => None,
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern: the runs with a
|
||||
/// glyph outline (list markers and ruby included) or an underline or strikethrough bar. Spaces and
|
||||
/// line breaks draw no outline. A type object's characters carry their own fill and stroke, and the
|
||||
/// type object's own fills and strokes paint on its characters, so only those runs paint. The type
|
||||
/// is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let is_pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
|
||||
let own = n.appearance.items.iter().any(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_pattern(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_pattern(&s.paint),
|
||||
});
|
||||
if !own && !t.runs.iter().any(|r| is_pattern(&r.style.fill) || is_pattern(&r.style.stroke)) {
|
||||
return None;
|
||||
}
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let resolved = d.inline_resolved(t);
|
||||
let lay = vectorcraft_text::layout(db, &resolved);
|
||||
let mut painted: BTreeSet<usize> = lay.glyphs.iter().chain(&lay.ruby).filter(|g| !g.outline.elements().is_empty()).map(|g| g.run).collect();
|
||||
painted.extend(vectorcraft_text::decorations(&lay, db, &resolved).into_iter().map(|(run, _)| run));
|
||||
Some((t, painted))
|
||||
}
|
||||
|
||||
/// The patterns `n`'s own fills and strokes paint, each once. A hidden fill or stroke and a stroke
|
||||
/// with no width paint nothing, and neither does any fill or stroke of a guide (drawn in the guide
|
||||
/// color), of a compound path's member (`members`: the compound path's own fills and strokes paint
|
||||
/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint
|
||||
/// only where an effect gives them a shape.
|
||||
fn own_patterns<'a>(
|
||||
n: &'a Node,
|
||||
members: &HashSet<*const Node>,
|
||||
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
|
||||
) -> Vec<&'a str> {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| members.contains(&std::ptr::from_ref(n))
|
||||
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
// The patterns an image's shaped fills and strokes paint (their effects can transform the
|
||||
// pattern, so they are matched by name).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)).then(|| {
|
||||
vectorcraft_render::effects::image_paint(n)
|
||||
.into_iter()
|
||||
.filter_map(|(_, _, item)| match item.paint() {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let mut out: Vec<&str> = vec![];
|
||||
for item in &n.appearance.items {
|
||||
let Paint::Pattern { pattern, .. } = item.paint() else { continue };
|
||||
let paints = item.visible()
|
||||
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(pattern));
|
||||
if paints && !out.contains(&pattern.as_str()) {
|
||||
out.push(pattern);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -293,9 +350,19 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
|
||||
let mut repeats: Vec<Value> = vec![];
|
||||
let mut repeat_rows: Vec<(String, String)> = vec![];
|
||||
// `pattern_objects` and `pattern_rows` hold the `patternObjects` entries and the rows of the objects filled or stroked with a pattern, in walk order.
|
||||
let mut pattern_objects: Vec<Value> = vec![];
|
||||
let mut pattern_rows: Vec<(String, String)> = vec![];
|
||||
// The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once.
|
||||
// The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two.
|
||||
let mut seen: HashSet<*const Node> = HashSet::new();
|
||||
// The members of the document's compound paths: the compound path's own fills and strokes paint them.
|
||||
let mut members: HashSet<*const Node> = HashSet::new();
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
members.extend(children.iter().map(|c| std::ptr::from_ref(&**c)));
|
||||
}
|
||||
});
|
||||
for r in roots {
|
||||
r.walk(&mut |n| {
|
||||
if !seen.insert(std::ptr::from_ref(n)) {
|
||||
@@ -345,16 +412,18 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The paint kinds this object's fills and strokes use, each once.
|
||||
let mut kinds = BTreeSet::new();
|
||||
// The patterns this object's fills and strokes use, each once.
|
||||
let mut used_patterns: Vec<&str> = vec![];
|
||||
let painted_runs = painted_runs(d, n);
|
||||
for pattern in own_patterns(n, &members, painted_runs.as_ref()) {
|
||||
patterns.insert(pattern.to_string());
|
||||
used_patterns.push(pattern);
|
||||
}
|
||||
for item in &n.appearance.items {
|
||||
let paint = match item {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => &f.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => &s.paint,
|
||||
};
|
||||
if let Some(k) = paint_kind(paint) {
|
||||
kinds.insert(k);
|
||||
}
|
||||
if let Paint::Pattern { pattern, .. } = paint {
|
||||
patterns.insert(pattern.clone());
|
||||
let paint = item.paint();
|
||||
// Objects counts an object with a pattern when Pattern Objects lists it, below.
|
||||
if let Paint::Gradient(_) = paint {
|
||||
kinds.insert("gradients");
|
||||
}
|
||||
if let Paint::Solid { swatch: Some(name), .. } = paint
|
||||
&& d.swatch(name).is_some_and(|s| s.spot)
|
||||
@@ -362,6 +431,28 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spot.insert(name.clone());
|
||||
}
|
||||
}
|
||||
// The characters' own paints: an inline graphic draws no outline and does not take its
|
||||
// run's paint (a list marker set in its run does), and a stroke with no width paints
|
||||
// nothing.
|
||||
if let Some((t, painted)) = &painted_runs {
|
||||
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
|
||||
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
|
||||
for paint in std::iter::once(&run.style.fill).chain(stroke) {
|
||||
if let Paint::Pattern { pattern, .. } = paint {
|
||||
patterns.insert(pattern.clone());
|
||||
if !used_patterns.contains(&pattern.as_str()) {
|
||||
used_patterns.push(pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !used_patterns.is_empty() {
|
||||
let name = n.display_name();
|
||||
pattern_objects.push(json!({ "id": n.id.0, "name": name, "patterns": used_patterns }));
|
||||
pattern_rows.push((name, used_patterns.join(", ")));
|
||||
kinds.insert("patterns");
|
||||
}
|
||||
for k in kinds {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
}
|
||||
@@ -412,10 +503,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"paragraphStyles": d.para_styles.len(),
|
||||
"patterns": d.patterns.len(),
|
||||
"patternNames": patterns,
|
||||
"patternObjects": pattern_objects,
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -634,6 +726,120 @@ mod tests {
|
||||
assert_eq!(i["sections"][0]["rows"][0], json!(["<Grid Repeat>", "Grid Repeat, 500 rows × 500 columns, 125000 instances"]));
|
||||
}
|
||||
|
||||
/// Document Info › Pattern Objects lists each object filled or stroked with a pattern once,
|
||||
/// with the patterns it uses, one in a group and a type object whose characters use a pattern
|
||||
/// included; a pattern no art uses adds no row, and Objects counts the listed objects. With
|
||||
/// Selection Only it lists the patterned objects in the selection, and the report writes the
|
||||
/// same rows.
|
||||
#[test]
|
||||
fn info_lists_the_pattern_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let square =
|
||||
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let tile = square(&mut s, 0.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
|
||||
let spare = square(&mut s, 20.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [spare], "name": "Unused", "edit": false})).unwrap();
|
||||
let (a, b, c) = (square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Dots"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a], "swatch": "Dots"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [b], "swatch": "Dots"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
// A type object whose characters are filled with the pattern.
|
||||
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Dots"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
|
||||
// A hidden pattern fill and a pattern stroke with no width paint nothing, so neither object is listed.
|
||||
let (d, e) = (square(&mut s, 100.0), square(&mut s, 200.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Dots"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Dots"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
|
||||
// A type object with no characters paints nothing either.
|
||||
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Dots"})).unwrap();
|
||||
// Its own fill (a copy of its characters' pattern fill) paints on its characters, so it paints nothing.
|
||||
s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
|
||||
// Nor does type of only spaces and a line break, or a guide made from a patterned path.
|
||||
let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Dots"})).unwrap();
|
||||
let guide = square(&mut s, 300.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Dots"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
// Nor does a compound path's member's own pattern fill: the compound path's own fill paints it.
|
||||
let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
|
||||
let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
|
||||
let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
|
||||
// Nor does an image's pattern fill without an effect that gives it a shape.
|
||||
let pic = square(&mut s, 360.0);
|
||||
s.execute("select.set", &json!({"ids": [pic]})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects[0];
|
||||
s.edit("own paint", |d, _| {
|
||||
d.node_mut(member).unwrap().appearance = paint.clone();
|
||||
d.node_mut(image).unwrap().appearance = paint;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Underlined spaces draw a bar in the pattern, so that type object is listed.
|
||||
let bar = s.execute("text.create", &json!({"x": 0, "y": 340, "text": " "})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [bar], "swatch": "Dots"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [bar]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"underline": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": bar, "name": "Bar"})).unwrap();
|
||||
// A list marker set in an inline graphic's run draws in that run's pattern, so that type object is listed.
|
||||
s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let listed = s.execute("text.create", &json!({"x": 0, "y": 360, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("text.insertInline", &json!({"id": listed, "at": 0, "symbol": "Mark"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [listed], "list": "bullet"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [listed], "swatch": "Dots"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": listed, "name": "Listed"})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
i["patternObjects"],
|
||||
json!([
|
||||
{"id": a, "name": "Both", "patterns": ["Dots"]},
|
||||
{"id": b, "name": "<Rectangle>", "patterns": ["Dots"]},
|
||||
{"id": t, "name": "Type", "patterns": ["Dots"]},
|
||||
{"id": bar, "name": "Bar", "patterns": ["Dots"]},
|
||||
{"id": listed, "name": "Listed", "patterns": ["Dots"]},
|
||||
])
|
||||
);
|
||||
assert_eq!(i["patternNames"], json!(["Dots"]));
|
||||
// Objects counts the objects that Pattern Objects lists.
|
||||
assert_eq!(i["objects"]["patterns"].as_u64(), Some(5), "{}", i["objects"]);
|
||||
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert!(i["objects"]["patterns"].is_null() && i["patternObjects"] == json!([]), "{}", i["objects"]);
|
||||
let i = s.execute("document.info", &json!({"category": "patterns"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("patterns"), Some("Pattern Objects")));
|
||||
assert_eq!(
|
||||
i["sections"][0]["rows"],
|
||||
json!([["Both", "Dots"], ["<Rectangle>", "Dots"], ["Type", "Dots"], ["Bar", "Dots"], ["Listed", "Dots"]])
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "patterns"})).unwrap();
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Dots"]]));
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "patterns"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["rows"].clone(), i["patternNames"].clone()), (json!([["Type", "Dots"]]), json!(["Dots"])));
|
||||
let text = s.execute("document.info", &json!({"category": "patterns", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nPATTERN OBJECTS\nBoth: Dots\n<Rectangle>: Dots\nType: Dots\nBar: Dots\nListed: Dots\n"), "{text}");
|
||||
assert!(!text.contains("Unused"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
|
||||
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
|
||||
/// it counts that object once.
|
||||
|
||||
@@ -14,7 +14,7 @@ pub(super) fn curvature(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "need at least one point"));
|
||||
}
|
||||
let sp = vectorcraft_tools::draw2::curvature_spline(&pts, switch_or(p, "closed", false, C)?);
|
||||
if let Some(id) = id_param(p, "id") {
|
||||
if let Some(id) = crate::cmd::object_param(p, "id", C)? {
|
||||
s.edit("Curvature", |d, sel| {
|
||||
*path_mut(d, id)? = PathData::single(sp);
|
||||
sel.set([id]);
|
||||
|
||||
+274
-11
@@ -9,9 +9,9 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req,
|
||||
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok,
|
||||
point_param, str_param, switch_or,
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_or, f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param,
|
||||
index, ok, point_param, str_param, switch_or,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -41,6 +41,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
|
||||
cmd!(
|
||||
query "document.compare",
|
||||
"Compare with Image",
|
||||
[],
|
||||
None,
|
||||
"{path: an image file (PNG, JPEG, WebP, TIFF or BMP), artboard?: index=0, background?: \"#rrggbb\"=\"#ffffff\" (the render and the image are both flattened on it), threshold?: 0.08 (0–1), diffPath?: a PNG to write (each pixel's absolute R, G and B differences)} render the artboard at the image's size (the image's width in pixels over the artboard's width in points), drawn as document.export draws a PNG (linked images and placed documents from their files), and compare it with the image; an image whose height differs by more than a pixel from the artboard's height at that scale is refused (not in the browser) → {width, height, rmse: the root mean square of the R, G and B differences, 0–1 (6 decimals), over: the pixels with a channel that differs by more than threshold, total: the pixels, threshold, diffPath?, warnings?: as a PNG export's (type that doesn't fit its frame, an image that couldn't be decoded, type in a font or style that isn't available, previews drawn because a linked file can't be read)}",
|
||||
has_doc,
|
||||
doc_compare
|
||||
),
|
||||
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))),
|
||||
cmd!(
|
||||
"document.setUnits",
|
||||
@@ -116,6 +125,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
can_clear_history,
|
||||
clear_history
|
||||
),
|
||||
cmd!(
|
||||
"edit.newDocumentFromState",
|
||||
"New Document from State",
|
||||
[],
|
||||
None,
|
||||
"{index?: a row of the History panel (0: the oldest state kept; default: the current state), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches)} make a new document holding the art as it was at that state, and make it the active document (the History panel's New Document from State button). The new document is named with the next Untitled-N, has nothing selected and no steps to undo or redo, is marked unsaved and links to the same files. It is out of symbol, opacity-mask and pattern editing, with the art drawn in a pattern's tile stored in the pattern as object.pattern.done stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step, as edit.undo keeps it; `index` names the row as it was listed before that. An index that names no state is an error and changes nothing → {index: the new document's, title}",
|
||||
has_doc,
|
||||
new_document_from_state
|
||||
),
|
||||
cmd!(
|
||||
"edit.undoGroup.begin",
|
||||
"Begin Undo Group",
|
||||
@@ -139,7 +157,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut",
|
||||
["Edit"],
|
||||
Some("Cmd+X"),
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)",
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (selected ruler guides go too; the Artboard tool chosen: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
cut
|
||||
),
|
||||
@@ -148,7 +166,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy",
|
||||
["Edit"],
|
||||
Some("Cmd+C"),
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}",
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
copy
|
||||
),
|
||||
@@ -202,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides); without ids, refused while an object of a symbol instance's art is selected",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -376,6 +394,155 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed
|
||||
/// documents from their files, with the export's warnings), and measure how far the
|
||||
/// two are apart: both flattened on `background`, the root mean square of the R, G and B
|
||||
/// differences (0–1), and the pixels with a channel that differs by more than `threshold`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn doc_compare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_render::encode::{RasterExportOptions, RasterFormat, png};
|
||||
const C: &str = "document.compare";
|
||||
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
let diff_path = match p.get("diffPath") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(v)) => Some(v.as_str()),
|
||||
Some(_) => {
|
||||
let key = "diffPath";
|
||||
return Err(bad(C, format!("`{key}` must be a string")));
|
||||
}
|
||||
};
|
||||
let background = match p.get("background") {
|
||||
None | Some(Value::Null) => [255; 3],
|
||||
Some(v) => match super::fileio::background(v) {
|
||||
Ok(Some(rgb)) => rgb,
|
||||
_ => return Err(bad(C, format!("background {v}: a color such as \"#808080\""))),
|
||||
},
|
||||
};
|
||||
let threshold = match p.get("threshold") {
|
||||
None | Some(Value::Null) => 0.08,
|
||||
Some(v) => v.as_f64().filter(|t| (0.0..=1.0).contains(t)).ok_or_else(|| bad(C, "`threshold` must be a number from 0 to 1"))?,
|
||||
};
|
||||
let doc = &s.doc()?.doc;
|
||||
let count = doc.artboards.len();
|
||||
let i = opt_u64(p, C, "artboard")?.unwrap_or(0);
|
||||
let region = usize::try_from(i)
|
||||
.ok()
|
||||
.and_then(|i| doc.artboards.get(i))
|
||||
.map(|a| a.rect)
|
||||
.ok_or_else(|| bad(C, format!("no artboard {i} (0-based; the document has {count})")))?;
|
||||
if let Some(d) = diff_path {
|
||||
crate::file_access::check_write(d).map_err(EngineError::Other)?;
|
||||
}
|
||||
let image = compare_image(path)?;
|
||||
let (iw, ih) = image.dimensions();
|
||||
// The image's width sets the scale; its height may differ from the artboard's at that scale by
|
||||
// the pixel the rounding of a render takes.
|
||||
let scale = f64::from(iw) / region.width();
|
||||
let rendered_height = region.height() * scale;
|
||||
if iw == 0 || ih == 0 || !rendered_height.is_finite() || (rendered_height - f64::from(ih)).abs() > 1.0 {
|
||||
let (rw, rh) = (iw, rendered_height.round());
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ"),
|
||||
));
|
||||
}
|
||||
vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?;
|
||||
vectorcraft_render::raster_size(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(iw), f64::from(ih)), 1.0).map_err(|e| bad(C, e))?;
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
let opts = RasterExportOptions { background: Some(background), ..Default::default() }.render_options(RasterFormat::Png);
|
||||
// As a PNG export: linked images and placed documents drawn from their files, not the
|
||||
// previews saved for them.
|
||||
let (full, linked) = super::place::document::full_documents(doc);
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let rendered = vectorcraft_render::Renderer::new().render(&full, iw, ih, view, &opts);
|
||||
// A canceled render stops drawing: the picture is not whole.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
// As a PNG export says, in its order: type on the artboard that doesn't fit its frame, an image
|
||||
// the renderer couldn't decode (missing from the render), type in a missing font or style (drawn
|
||||
// in another one), and linked files drawn from their previews.
|
||||
let mut warnings: Vec<String> = super::fonts::export_overflow_warning(&full, &full.layers, Some(&[region])).into_iter().collect();
|
||||
if let Some(w) = super::rasterfx::undecoded_warning(failed) {
|
||||
warnings.push(w.into());
|
||||
}
|
||||
if let Some(w) = super::fonts::substitution_warning(&full) {
|
||||
warnings.push(w);
|
||||
}
|
||||
warnings.extend(linked);
|
||||
let rendered = rendered.to_straight();
|
||||
let flat = |px: &[u8; 4]| {
|
||||
let a = u32::from(px[3]);
|
||||
[0, 1, 2].map(|k| ((u32::from(px[k]) * a + u32::from(background[k]) * (255 - a) + 127) / 255) as u8)
|
||||
};
|
||||
let row = iw as usize * 4;
|
||||
let limit = threshold * 255.0;
|
||||
let (mut squares, mut over) = (0.0f64, 0u64);
|
||||
let mut diff = diff_path.map(|_| Vec::with_capacity(row * ih as usize));
|
||||
for (a, b) in rendered.chunks_exact(row).zip(image.as_raw().chunks_exact(row)) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
for (pa, pb) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) {
|
||||
let (fa, fb) = (flat(pa), flat(pb));
|
||||
let d = [0, 1, 2].map(|k| fa[k].abs_diff(fb[k]));
|
||||
squares += d.iter().map(|&x| f64::from(x) * f64::from(x)).sum::<f64>();
|
||||
if d.iter().any(|&x| f64::from(x) > limit) {
|
||||
over += 1;
|
||||
}
|
||||
if let Some(out) = &mut diff {
|
||||
out.extend_from_slice(&[d[0], d[1], d[2], 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let total = u64::from(iw) * u64::from(ih);
|
||||
let rmse = (squares / (total as f64 * 3.0)).sqrt() / 255.0;
|
||||
let mut out = json!({
|
||||
"width": iw,
|
||||
"height": ih,
|
||||
"rmse": (rmse * 1e6).round() / 1e6,
|
||||
"over": over,
|
||||
"total": total,
|
||||
"threshold": threshold,
|
||||
});
|
||||
if let (Some(d), Some(pixels)) = (diff_path, diff) {
|
||||
let bytes = png::encode(&pixels, iw, ih, &png::PngOptions { ppi: None, interlaced: false }).map_err(EngineError::Other)?;
|
||||
super::fileio::write_file(d, &bytes)?;
|
||||
out["diffPath"] = json!(d);
|
||||
}
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The image `document.compare` reads from `path` (through the automation read root), as straight
|
||||
/// RGBA: a PNG, JPEG, WebP, TIFF or BMP within the allocation an opened image may take.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn compare_image(path: &str) -> Result<image::RgbaImage> {
|
||||
use image::ImageDecoder as _;
|
||||
const C: &str = "document.compare";
|
||||
let bytes = super::fileio::read_file(path)?;
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(&bytes) {
|
||||
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(C, format!("{path}: {e}")))?;
|
||||
let readable = [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::WebP, image::ImageFormat::Tiff, image::ImageFormat::Bmp];
|
||||
if !reader.format().is_some_and(|f| readable.contains(&f)) {
|
||||
return Err(bad(C, format!("{path}: not a PNG, JPEG, WebP, TIFF or BMP image")));
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
let decoder = reader.into_decoder().map_err(|e| bad(C, format!("{path}: {e}")))?;
|
||||
let (w, h) = decoder.dimensions();
|
||||
if decoder.total_bytes() > vectorcraft_doc::MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > vectorcraft_doc::MAX_RASTER_ALLOC {
|
||||
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
Ok(image::DynamicImage::from_decoder(decoder).map_err(|e| bad(C, format!("{path}: {e}")))?.to_rgba8())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn doc_compare(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("document.compare", "comparing with an image file isn't available in the browser"))
|
||||
}
|
||||
|
||||
/// Document Setup's units (also `document.setup {units}`).
|
||||
fn set_units(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let u = str_param(p, "units").and_then(Unit::named).ok_or_else(|| bad("document.setUnits", "unknown units"))?;
|
||||
@@ -606,6 +773,53 @@ fn clear_history(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "cleared": cleared }))
|
||||
}
|
||||
|
||||
/// History panel › New Document from State: a new document with the art of a state, and without
|
||||
/// the editing state that state may hold (opacity-mask or symbol editing, Puppet Warp pins, new art).
|
||||
/// Its links point at the files the source finds, which may be in the source's folder away from
|
||||
/// the links' paths. Later artboards in the two documents take their ids separately. A later save of the new document
|
||||
/// over the file its art was read from asks first, as a save of the source does.
|
||||
fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.newDocumentFromState";
|
||||
let created = date_param(p, "created", C)?;
|
||||
let st = s.doc()?;
|
||||
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
|
||||
let chosen = match p.get("index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row)));
|
||||
Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
|
||||
}
|
||||
};
|
||||
settle_interaction(s)?;
|
||||
let st = s.doc()?;
|
||||
let mut doc = Document::clone(chosen.as_ref().unwrap_or(&st.doc));
|
||||
let (imported_from, import_losses, opened_by) = (st.imported_from.clone(), st.import_losses.clone(), st.opened_by.clone());
|
||||
if let Some(path) = st.path.as_deref() {
|
||||
// Files are looked for within the asking caller's roots, else within those of the caller that opened the source.
|
||||
let roots = crate::file_access::current().or_else(|| opened_by.clone());
|
||||
crate::file_access::confine(roots.as_ref(), || super::links::with_found_paths(&mut doc, path));
|
||||
}
|
||||
doc.drop_edit_modes();
|
||||
if doc.pattern_edit.is_some() {
|
||||
super::patterncmds::finish_edit(&mut doc, &mut vectorcraft_doc::Selection::default())?;
|
||||
}
|
||||
doc.puppet = None;
|
||||
doc.new_art.set(Arc::default());
|
||||
let retired = vectorcraft_doc::RetiredArtboardId::default();
|
||||
retired.raise(doc.retired_artboard_id.get());
|
||||
doc.retired_artboard_id = retired;
|
||||
doc.title = s.next_untitled();
|
||||
doc.metadata.created = clock_date(s, "created", created);
|
||||
doc.metadata.modified = None;
|
||||
let i = s.add_document(doc, None);
|
||||
let st = s.doc_mut()?;
|
||||
st.imported_from = imported_from;
|
||||
st.import_losses = import_losses;
|
||||
st.opened_by = st.opened_by.take().or(opened_by);
|
||||
st.mark_unsaved();
|
||||
Ok(json!({ "index": i, "title": st.title() }))
|
||||
}
|
||||
|
||||
/// `selection` for an undo (redo) step, sharing that of `like`, the step beside it, when the same.
|
||||
fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::HistoryEntry>) -> Arc<vectorcraft_doc::Selection> {
|
||||
match like {
|
||||
@@ -615,16 +829,38 @@ fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::
|
||||
}
|
||||
|
||||
/// Selected top-level objects in paint order, dropping any whose ancestor is also selected.
|
||||
///
|
||||
/// Refused with [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art
|
||||
/// is selected ([`super::brushsym::selected_part`]): only the paint commands change that object,
|
||||
/// and only its solid fill and stroke, so a command that gathers the selection here leaves the
|
||||
/// instance as it is. Copy copies the instance whole ([`copy_cut_targets`]).
|
||||
pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_of(&st.doc, st.selection.in_paint_order(&st.doc)))
|
||||
}
|
||||
|
||||
/// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected:
|
||||
/// for the commands that read the selected objects without [`selected_roots`]. A command that
|
||||
/// changes nothing in the document ([`Session::reading`]) reads the instance instead.
|
||||
pub(crate) fn refuse_symbol_part(s: &Session) -> Result<()> {
|
||||
if !s.reading && s.doc()?.selection.symbol_part.is_some() { Err(super::brushsym::part_only()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// [`refuse_symbol_part`] as a command's `enabled` check: the command is dimmed, and refused with
|
||||
/// [`super::brushsym::part_only`]'s message, while an object of a dynamic symbol instance's art is
|
||||
/// selected.
|
||||
pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> {
|
||||
if !s.reading && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { Err(super::brushsym::part_only().to_string()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// [`selected_roots`] for the commands that move or reshape the art (Move, Transform, Rotate…): a
|
||||
/// path of a compound path selected on its own (Group Selection, or in the isolated compound path)
|
||||
/// is an object of its own, so the hole of a ring moves without the ring (#2441). Paint and the
|
||||
/// rest still go to the compound path, which holds the paint.
|
||||
/// rest still go to the compound path, which holds the paint. Refused while an object of a symbol
|
||||
/// instance's art is selected, as [`selected_roots`] is: it moves with its instance only.
|
||||
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
|
||||
}
|
||||
@@ -633,8 +869,10 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
/// ([`super::inside_isolation`]): `root` itself and objects outside it are left out before the
|
||||
/// objects held by another selected object are dropped. A selected path of a compound path stands
|
||||
/// for its compound unless the compound is `root` or `members` is set (as in
|
||||
/// [`selected_roots_to_transform`]).
|
||||
/// [`selected_roots_to_transform`]). Refused while an object of a symbol instance's art is
|
||||
/// selected, as [`selected_roots`] is.
|
||||
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
|
||||
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
|
||||
@@ -692,7 +930,10 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option<Vec<usize>>)>) -> i
|
||||
/// The direct-selection flag and resolved root nodes for Copy and Cut operations.
|
||||
fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
|
||||
let st = s.doc()?;
|
||||
let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature");
|
||||
// The Pen and the Curvature tool leave the anchor they placed or edited selected: Copy takes
|
||||
// the whole path then (#2122), unless a selection tool Cmd lent them picked the anchors (#6123).
|
||||
let picked = s.lent_selection.as_ref().is_some_and(|(uid, sel)| *uid == st.uid && *sel == st.selection);
|
||||
let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature") && !picked;
|
||||
let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty());
|
||||
let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
|
||||
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| {
|
||||
@@ -711,6 +952,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), false);
|
||||
}
|
||||
// With an object of a dynamic symbol instance's art selected, the instance is copied.
|
||||
let (direct, targets) = copy_cut_targets(s)?;
|
||||
let st = s.doc()?;
|
||||
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
|
||||
@@ -751,6 +993,7 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), true);
|
||||
}
|
||||
refuse_symbol_part(s)?;
|
||||
// Ruler guides selected on their own: Copy takes them, Clear removes them.
|
||||
if s.doc()?.selection.is_empty() {
|
||||
copy(s, p)?;
|
||||
@@ -824,6 +1067,10 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
// An object of a symbol instance's art can't be removed from the instance alone.
|
||||
if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
// Direct-selected anchors or segments: remove those, and any objects selected whole with them.
|
||||
if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) {
|
||||
return super::path::delete_anchors(s, p);
|
||||
@@ -1055,10 +1302,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
imported.apply(&mut c);
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
// A cross-document drag carries the graphic's appearance with it,
|
||||
// including the pattern phase, independently of transform-tool settings.
|
||||
c.transform(xf, vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() });
|
||||
c.transform(xf, sc);
|
||||
}
|
||||
let layer = match clip.source_layers.get(k) {
|
||||
Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))),
|
||||
@@ -1094,6 +1342,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
if let NodeKind::Path { live, .. } = &mut child_node.kind {
|
||||
*live = None;
|
||||
}
|
||||
if child_node.extras().pixel_aligned {
|
||||
child_node.extras_mut().pixel_aligned = false;
|
||||
}
|
||||
let insert_idx = if idx == usize::MAX { usize::MAX } else { idx.saturating_add(offset) };
|
||||
new_ids.push(d.insert(par, insert_idx, child_node)?);
|
||||
}
|
||||
@@ -1106,6 +1357,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
if let NodeKind::Path { live, .. } = &mut c.kind {
|
||||
*live = None;
|
||||
}
|
||||
// A path inside a compound path snaps with the compound path, whose property it takes.
|
||||
if c.extras().pixel_aligned {
|
||||
c.extras_mut().pixel_aligned = false;
|
||||
}
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
}
|
||||
_ => {
|
||||
@@ -1114,14 +1369,19 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let offset = *placed.entry(outer_par).or_default();
|
||||
*placed.entry(outer_par).or_default() += 1;
|
||||
let insert_idx = if beside_idx == usize::MAX { usize::MAX } else { beside_idx.saturating_add(offset) };
|
||||
super::object::keep_pixel_aligned(&mut c, sc);
|
||||
new_ids.push(d.insert(outer_par, insert_idx, c)?);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
super::object::keep_pixel_aligned(&mut c, sc);
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
for id in &new_ids {
|
||||
super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default());
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
|
||||
// paste of guides alone keeps them where they were, but onto another artboard or every
|
||||
@@ -1193,7 +1453,10 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Duplicate `roots` directly above each original, transform the copies, select them
|
||||
/// ([`copy_above`]).
|
||||
pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selection, roots: &[NodeId], xf: Affine) -> Result<Vec<NodeId>> {
|
||||
let out = copy_above(d, roots, |_, _, c| c.transform(xf, true))?;
|
||||
let out = copy_above(d, roots, |_, _, c| {
|
||||
c.transform(xf, true);
|
||||
super::object::keep_pixel_aligned(c, true.into());
|
||||
})?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,22 @@ use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param, switch_or};
|
||||
|
||||
/// The name of the `svg.filter` effect drawing `xml`: its `<filter>` id. An effect names the
|
||||
/// document's filter of that name, so `xml` that differs from the document's filter of the same
|
||||
/// name is refused.
|
||||
fn svg_filter_name(s: &Session, xml: &str, cmd: &str) -> Result<String> {
|
||||
let name = effects::svg_filter::check(xml).map_err(|e| bad(cmd, e))?;
|
||||
if let Some(held) = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name)
|
||||
&& held.xml != xml.trim()
|
||||
{
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("the document has another SVG filter named {name:?}: use svgFilter.apply, or svgFilter.define with `replace` to edit it"),
|
||||
));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// The effect commands of the Effect menu and the Appearance panel.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -35,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Effects",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: object ids (default: the selection), target?: \"object\"|\"contents\"} → {catalog: [{id, label, menu, params, defaults, raster, lengths: {always, absolute (while relative is false)} (distance params Scale Strokes & Effects scales)}] (installed effect plug-ins last: id plugin.<plug-in id>, menu Effect › Plug-ins), applied: [{id, effects, items: [{index, kind: fill|stroke, effects}]}], activeItem} for the selection",
|
||||
"{ids?|id?: object ids (default: the selection), target?: \"object\"|\"contents\"} → {catalog: [{id, label, menu, params, defaults, raster, lengths: {always, absolute (while relative is false)} (distance params Scale Strokes & Effects scales)}] (installed effect plug-ins last: id plugin.<plug-in id>, menu Effect › Plug-ins), applied: [{id, effects, items: [{index, kind: fill|stroke, effects}]}] (an effect has skipped: true while Safe Mode skips it: a plug-in effect, which the object keeps and draws without), activeItem} for the selection",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -53,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Effect Options",
|
||||
[],
|
||||
None,
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
|
||||
has_doc,
|
||||
set_params
|
||||
),
|
||||
@@ -71,7 +87,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; 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. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. 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. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. 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
|
||||
),
|
||||
@@ -222,6 +238,16 @@ pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existin
|
||||
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.apply";
|
||||
let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?;
|
||||
// An effect given as `id` names no objects: the targets are read with that `id` as null.
|
||||
let effect_as_id;
|
||||
let p = if str_param(p, "effect").is_none() {
|
||||
let mut q = p.clone();
|
||||
q["id"] = Value::Null;
|
||||
effect_as_id = q;
|
||||
&effect_as_id
|
||||
} else {
|
||||
p
|
||||
};
|
||||
let mut params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
if !params.is_null() && !params.is_object() {
|
||||
return Err(bad(C, "`params` must be an object"));
|
||||
@@ -235,6 +261,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if texture_load_effect(id) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
// An SVG filter needs its <filter> element, and is named by its id.
|
||||
if id == effects::SVG_FILTER {
|
||||
let xml = params.get("xml").and_then(Value::as_str).ok_or_else(|| bad(C, "give `xml`, one SVG <filter> element"))?;
|
||||
params["name"] = json!(svg_filter_name(s, xml, C)?);
|
||||
}
|
||||
let effect = effects::new_effect(id, ¶ms).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?;
|
||||
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
|
||||
aligned(p, C)?;
|
||||
@@ -297,7 +328,22 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect();
|
||||
let mut applied = vec![];
|
||||
if s.active().is_some() {
|
||||
let fx = |e: &[Effect]| serde_json::to_value(e).unwrap_or(Value::Null);
|
||||
// A plug-in effect Safe Mode skips says so (`skipped`): the object keeps it.
|
||||
let fx = |e: &[Effect]| {
|
||||
Value::Array(
|
||||
e.iter()
|
||||
.map(|e| {
|
||||
let mut v = serde_json::to_value(e).unwrap_or(Value::Null);
|
||||
if vectorcraft_plugins::effect::skipped(&e.id)
|
||||
&& let Some(o) = v.as_object_mut()
|
||||
{
|
||||
o.insert("skipped".into(), json!(true));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
for id in appearance_targets(s, p)? {
|
||||
if let Some(n) = s.doc()?.doc.node(id) {
|
||||
let items: Vec<Value> = n
|
||||
@@ -422,10 +468,28 @@ pub(crate) fn set_params_effects(s: &Session, p: &Value) -> Vec<String> {
|
||||
return vec![];
|
||||
};
|
||||
let Ok(targets) = effect_targets(s, p, item, index, C) else { return vec![] };
|
||||
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| Some(st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id.clone());
|
||||
// A 3D effect whose type `threeDType` changes takes the new effect's parameters.
|
||||
let kind = three_d_type(p, C).ok().flatten();
|
||||
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| {
|
||||
let id = &st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id;
|
||||
Some(kind.filter(|_| effects::is_three_d(id)).map_or_else(|| id.clone(), str::to_string))
|
||||
};
|
||||
targets.iter().filter_map(effect).collect()
|
||||
}
|
||||
|
||||
/// The effect `threeDType` in `p` turns a 3D effect into ([`effects::THREE_D_TYPES`]), when given.
|
||||
fn three_d_type(p: &Value, cmd: &str) -> Result<Option<&'static str>> {
|
||||
let key = "threeDType";
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
match v.as_str().and_then(|t| effects::THREE_D_TYPES.iter().find(|(name, _)| *name == t)) {
|
||||
Some((_, id)) => Ok(Some(id)),
|
||||
None => {
|
||||
let names: Vec<&str> = effects::THREE_D_TYPES.iter().map(|(name, _)| *name).collect();
|
||||
Err(bad(cmd, format!("`{key}` must be one of {}", names.join(", "))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.lightingPreset";
|
||||
let patch = str_param(p, "preset")
|
||||
@@ -450,8 +514,9 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `effect.setParams`: merges `params` into the effect at `index` of the targets' active item, and
|
||||
/// sets its Warp style (`warpStyle`) or visibility (`visible`), as one undo step. They are checked
|
||||
/// as `effect.apply` checks them, and a visible 3D effect must still fit. → `{ids}`.
|
||||
/// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one
|
||||
/// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still
|
||||
/// fit. → `{ids}`.
|
||||
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.setParams";
|
||||
let index = index_param(p, "index", C)?;
|
||||
@@ -459,6 +524,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !params.is_null() && !params.is_object() {
|
||||
return Err(bad(C, "`params` must be an object"));
|
||||
}
|
||||
let kind = three_d_type(p, C)?;
|
||||
let warp_id = p
|
||||
.get("warpStyle")
|
||||
.map(|v| -> Result<String> {
|
||||
@@ -476,21 +542,47 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if edited.iter().any(|e| texture_load_effect(e)) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
for (id, target, index) in effect_targets(s, p, item, index, C)? {
|
||||
let targets = effect_targets(s, p, item, index, C)?;
|
||||
// The type each 3D effect already has, with nothing else to change, is no edit (and is not
|
||||
// checked again).
|
||||
let nothing_else = params.as_object().is_none_or(serde_json::Map::is_empty) && visible.is_none() && warp_id.is_none();
|
||||
if let Some(to) = kind
|
||||
&& nothing_else
|
||||
{
|
||||
let d = &s.doc()?.doc;
|
||||
// The effects edited: a target without an effect at `index` is left as it is.
|
||||
let ids: Vec<&str> =
|
||||
targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index).map(|e| e.id.as_str())).collect();
|
||||
if !ids.is_empty() && ids.iter().all(|id| *id == to) {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// An SVG filter is named by its id: another filter renames the effect.
|
||||
if edited.iter().any(|e| e == effects::SVG_FILTER)
|
||||
&& let Some(xml) = params.get("xml").and_then(Value::as_str)
|
||||
{
|
||||
params["name"] = json!(svg_filter_name(s, xml, C)?);
|
||||
}
|
||||
for &(id, target, index) in &targets {
|
||||
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let effect = n.appearance.effects_at(target).and_then(|fx| fx.get(index));
|
||||
if warp_id.is_some() && effect.is_some_and(|e| e.id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_none()) {
|
||||
return Err(bad(C, "warpStyle can only edit an applied Warp effect"));
|
||||
}
|
||||
if kind.is_some() && effect.is_some_and(|e| !effects::is_three_d(&e.id)) {
|
||||
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
|
||||
}
|
||||
if let Some(e) = effect
|
||||
&& effects::is_three_d(&e.id)
|
||||
&& visible != Some(false)
|
||||
{
|
||||
let mut prospective = effects::merged_params(&e.id, &e.params);
|
||||
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(&e.id, ¶ms)) {
|
||||
let to = kind.unwrap_or(&e.id);
|
||||
let mut prospective =
|
||||
if to == e.id { effects::merged_params(&e.id, &e.params) } else { effects::three_d_params_as(&e.id, &e.params, to) };
|
||||
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, ¶ms)) {
|
||||
cur.extend(new);
|
||||
}
|
||||
effects::validate_three_d(n, &e.id, &prospective).map_err(|e| bad(C, e))?;
|
||||
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
|
||||
}
|
||||
}
|
||||
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
@@ -498,6 +590,12 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(id) = &warp_id {
|
||||
e.id.clone_from(id);
|
||||
}
|
||||
if let Some(to) = kind
|
||||
&& e.id != to
|
||||
{
|
||||
e.params = effects::three_d_params_as(&e.id, &e.params, to);
|
||||
e.id = to.to_string();
|
||||
}
|
||||
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) {
|
||||
if !cur.is_object() {
|
||||
*cur = effects::merged_params(&e.id, &Value::Null);
|
||||
@@ -823,8 +921,40 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
changed.then_some(n)
|
||||
}
|
||||
|
||||
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
|
||||
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
|
||||
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's
|
||||
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
|
||||
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
|
||||
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
|
||||
let mut symbols = vec![];
|
||||
let mut holds = false;
|
||||
n.walk(&mut |c| {
|
||||
if !in_art && !expandable(c) {
|
||||
return;
|
||||
}
|
||||
holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin));
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
symbols.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
holds
|
||||
|| symbols.into_iter().any(|name| {
|
||||
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
|
||||
})
|
||||
}
|
||||
|
||||
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = appearance_targets(s, p)?;
|
||||
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
|
||||
// geometry it hasn't changed.
|
||||
if vectorcraft_plugins::safe_mode::active() {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
if roots.iter().filter_map(|id| d.node(*id)).any(|n| holds_plugin_effect(d, n, false, &mut seen)) {
|
||||
return Err(EngineError::Other("Expand Appearance: a plug-in effect in the selection can't be expanded in Safe Mode".into()));
|
||||
}
|
||||
}
|
||||
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, _| {
|
||||
@@ -859,5 +989,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod lighting_presets_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod three_d_type_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,144 @@
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn setup(effect: &str, params: Value) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":params})).unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn effect(s: &Session, id: NodeId) -> (String, Value) {
|
||||
let e = &s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0];
|
||||
(e.id.clone(), e.params.clone())
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_turns_the_effect_in_place_keeping_shared_settings_in_one_undo_step() {
|
||||
let types = [("plane", "threeD.rotate"), ("extrude", "threeD.extrude"), ("revolve", "threeD.revolve"), ("inflate", "threeD.inflate")];
|
||||
for (from_type, from) in types {
|
||||
for (to_type, to) in types {
|
||||
if from == to {
|
||||
continue;
|
||||
}
|
||||
let (mut s, id) = setup(from, json!({"rotationX": 12.0, "rotationY": -30.0, "rotationZ": 5.0, "ambient": 40.0, "lightIntensity": 55.0}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
let p = json!({"index": 0, "item": null, "threeDType": to_type});
|
||||
s.check_params("effect.setParams", &p).unwrap();
|
||||
s.execute("effect.setParams", &p).unwrap();
|
||||
let (now, params) = effect(&s, id);
|
||||
assert_eq!(now, to, "{from_type} → {to_type}");
|
||||
assert_eq!(params["rotationX"], 12.0, "{from_type} → {to_type}");
|
||||
assert_eq!(params["rotationY"], -30.0);
|
||||
assert_eq!(params["ambient"], 40.0);
|
||||
assert_eq!(params["lightIntensity"], 55.0);
|
||||
// Settings only the new effect takes start at its defaults; others are dropped.
|
||||
let defaults = vectorcraft_render::effects::default_params(to).unwrap();
|
||||
for key in params.as_object().unwrap().keys() {
|
||||
assert!(defaults.get(key).is_some(), "{from_type} → {to_type} kept `{key}`");
|
||||
}
|
||||
if to == "threeD.extrude" {
|
||||
assert_eq!(params["bevel"], defaults["bevel"]);
|
||||
}
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_carries_depth_between_extrude_and_inflate_and_merges_params_after() {
|
||||
let (mut s, id) = setup("threeD.extrude", json!({"depth": 80.0, "twist": 30.0, "bevel": "classic"}));
|
||||
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "inflate", "params": {"volume": 70.0}})).unwrap();
|
||||
let (now, params) = effect(&s, id);
|
||||
assert_eq!(now, "threeD.inflate");
|
||||
assert_eq!(params["depth"], 80.0);
|
||||
assert_eq!(params["twist"], 30.0);
|
||||
assert_eq!(params["volume"], 70.0);
|
||||
assert!(params.get("bevel").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_angles_outside_half_a_turn_wrap_when_the_type_leaves_revolve() {
|
||||
let (mut s, id) = setup("threeD.revolve", json!({"rotationX": 270.0, "rotationY": -200.0}));
|
||||
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "plane"})).unwrap();
|
||||
let (_, params) = effect(&s, id);
|
||||
assert_eq!(params["rotationX"], -90.0);
|
||||
assert_eq!(params["rotationY"], 160.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_type_alone_changes_nothing_and_records_no_undo_step() {
|
||||
let (mut s, id) = setup("threeD.extrude", json!({"depth": 80.0}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
let r = s.execute("effect.setParams", &json!({"index": 0, "threeDType": "extrude"})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert_eq!(undo_len(&s), history);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// With other changes the edit runs as usual.
|
||||
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "extrude", "params": {"depth": 90.0}})).unwrap();
|
||||
assert_eq!(effect(&s, id).1["depth"], 90.0);
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_type_with_an_object_without_effects_selected_too_records_no_undo_step() {
|
||||
let (mut s, a) = setup("threeD.extrude", json!({}));
|
||||
let b = NodeId(s.execute("path.create", &json!({"d":"M250 100L350 100L350 200L250 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "aligned": true, "threeDType": "extrude"})).unwrap();
|
||||
assert_eq!(undo_len(&s), history);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_rejects_unknown_types_and_effects_that_are_not_3d() {
|
||||
let (mut s, _) = setup("threeD.extrude", json!({}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for t in [json!("cube"), json!(""), json!(null), json!(2), json!("Plane"), json!("plane/../x")] {
|
||||
let p = json!({"index": 0, "threeDType": t});
|
||||
let err = s.execute("effect.setParams", &p).unwrap_err().to_string();
|
||||
assert!(err.contains("must be one of plane, extrude, revolve, inflate"), "{t}: {err}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
|
||||
let err = s.execute("effect.setParams", &json!({"index": 1, "threeDType": "plane"})).unwrap_err().to_string();
|
||||
assert!(err.contains("needs a 3D effect at index 1"), "{err}");
|
||||
let err = s.execute("effect.setParams", &json!({"index": 5, "threeDType": "plane"})).unwrap_err().to_string();
|
||||
assert!(err.contains("no effect at index 5"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_turns_every_selected_object_in_one_undo_step() {
|
||||
let (mut s, a) = setup("threeD.rotate", json!({}));
|
||||
let b = NodeId(s.execute("path.create", &json!({"d":"M250 100L350 100L350 200L250 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color":"#d63333"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.rotate","item":null})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let history = undo_len(&s);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "aligned": true, "threeDType": "extrude"})).unwrap();
|
||||
assert_eq!(effect(&s, a).0, "threeD.extrude");
|
||||
assert_eq!(effect(&s, b).0, "threeD.extrude");
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_for_the_new_type_pass_the_parameter_check() {
|
||||
let (s, _) = setup("threeD.rotate", json!({}));
|
||||
// `depth` is an Extrude & Bevel setting, checked against the effect the type makes.
|
||||
s.check_params("effect.setParams", &json!({"index": 0, "threeDType": "extrude", "params": {"depth": 20.0}})).unwrap();
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place.
|
||||
//! - `mesh3d`: 3D assets as OBJ, glTF, USDA and USDZ mesh files (`assets.export3D`).
|
||||
//!
|
||||
//! [`FORMATS`] is the single list of formats (append-only); open dialogs use [`open_filters`],
|
||||
//! agents query `document.formats`.
|
||||
@@ -32,7 +33,9 @@ mod export;
|
||||
pub(crate) mod imagemap;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
mod heifread;
|
||||
mod jp2read;
|
||||
mod metafile;
|
||||
mod naming;
|
||||
@@ -54,6 +57,7 @@ pub mod zip;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use action_batch::batch_overwrites_one_file;
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
|
||||
pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
@@ -72,6 +76,8 @@ pub use load::{
|
||||
read_for_open, texture_image,
|
||||
};
|
||||
pub use load::{losses_summary, overwrite_losses};
|
||||
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
|
||||
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
@@ -123,7 +129,9 @@ pub(crate) use access::{drive_share_path, share_path, touched};
|
||||
pub(crate) use access::{may_read, may_write};
|
||||
pub use commands::specs;
|
||||
pub use export_names::artboard_file_names;
|
||||
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
|
||||
pub(crate) use export_names::{
|
||||
artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return,
|
||||
};
|
||||
use export_names::{distinct_names_by, write_encoded};
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
|
||||
pub use formats::{
|
||||
@@ -202,6 +210,8 @@ mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_heifread;
|
||||
#[cfg(test)]
|
||||
mod tests_jp2read;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -95,11 +95,93 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
match source {
|
||||
"folder" => batch_folder(s, C, p, override_open, &run),
|
||||
"datasets" => batch_datasets(s, C, &run),
|
||||
"datasets" => {
|
||||
let one_file = batch_overwrites_one_file(s, p);
|
||||
let mut r = batch_datasets(s, C, &run)?;
|
||||
if one_file {
|
||||
r["warning"] = json!(ONE_FILE_WARNING);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
_ => Err(bad(C, "`source` must be `folder` or `datasets`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `warning` of a Data Sets batch for which [`batch_overwrites_one_file`] holds.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const ONE_FILE_WARNING: &str = "each data set saves over the same file, which keeps only the last data set";
|
||||
|
||||
/// Whether an `action.batch` with params `p` plays on data sets of the open document in `s` and
|
||||
/// writes each data set to the same file. Save and Close saves the open document over its own file
|
||||
/// after every data set, unless a Save step that Override Save points into `destinationFolder`
|
||||
/// first makes each data set's file the document's own. A step that the batch does not point into `destinationFolder` writes the
|
||||
/// same file every time when it writes one: a Save, Save As, Save a Copy, Save as Template, Export,
|
||||
/// Export Selection, PDF, EPS, DXF, Save for Web or Save for Office Documents step that gives a
|
||||
/// `path`; a Save step without a `path` when the document has a file of its own (saved, and not
|
||||
/// converted from an older version or restored by Data Recovery) and the step gives no `format` or
|
||||
/// the document's own; an Export for Screens step whose `folder`, given or from its
|
||||
/// `exportPreset`, names a folder, whatever the overrides.
|
||||
/// Other steps return their data instead of writing a file.
|
||||
pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
|
||||
if p.get("source").and_then(Value::as_str) != Some("datasets") {
|
||||
return false;
|
||||
}
|
||||
let folder = p.get("destinationFolder").and_then(Value::as_str).is_some();
|
||||
let redirected = |key: &str| folder && p.get(key).and_then(Value::as_bool).unwrap_or(true);
|
||||
let (save, export) = (redirected("overrideSave"), redirected("overrideExport"));
|
||||
let steps = p.get("commands").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
|
||||
if p.get("destination").and_then(Value::as_str) == Some("saveAndClose") && !saves_move_to_each_file(steps, save) {
|
||||
return true;
|
||||
}
|
||||
// The format of the open document's own file, which a Save step without a `path` writes.
|
||||
let own_format = s.active().filter(|st| st.path.is_some() && !st.converted && !st.recovered).map(|st| st.format);
|
||||
let names = |v: Option<&Value>| v.and_then(Value::as_str).is_some_and(|s| !s.is_empty());
|
||||
steps.iter().any(|c| {
|
||||
let params = c.get("params").cloned().unwrap_or_else(|| Value::Object(Default::default()));
|
||||
let path = names(params.get("path"));
|
||||
let own_file = || match params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()) {
|
||||
None => own_format.is_some(),
|
||||
Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)),
|
||||
};
|
||||
match c.get("command").and_then(Value::as_str).unwrap_or("") {
|
||||
"document.save" | "file.save" => !save && (path || own_file()),
|
||||
"file.saveAs" => !save && path,
|
||||
"file.saveCopy" | "file.saveAsTemplate" => path,
|
||||
"document.export" | "document.exportSelection" => !export && path,
|
||||
// The batch does not point these exports into `destinationFolder`.
|
||||
"document.exportPdf" | "document.exportEps" | "document.exportDxf" | "document.exportForWeb" | "document.exportForOffice" => path,
|
||||
// Override Export sets `path`, which Export for Screens does not read: its `folder` stays.
|
||||
"document.exportForScreens" => super::screens::with_preset(s, ¶ms).is_ok_and(|p| names(p.get("folder"))),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `steps` hold a Save, Save As or `document.save` step that Override Save points at each
|
||||
/// data set's own file in the destination folder (`redirected`). Such a step makes that file the
|
||||
/// document's own, so Save and Close then saves each data set to its own file.
|
||||
fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool {
|
||||
redirected && steps.iter().any(|c| retargeting_save(c, true))
|
||||
}
|
||||
|
||||
/// Whether step `c` is a Save, Save As or `document.save` that writes a file (its own `path`, or one
|
||||
/// in the destination folder when `redirected`) and makes that file the document's own: a save in
|
||||
/// the native template format writes a copy and leaves the document's file as it was.
|
||||
fn retargeting_save(c: &Value, redirected: bool) -> bool {
|
||||
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) {
|
||||
return false;
|
||||
}
|
||||
let params = c.get("params");
|
||||
let path = params.and_then(|p| p.get("path")).and_then(Value::as_str).filter(|p| !p.is_empty());
|
||||
let format_ok = match params.and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()) {
|
||||
Some(f) => super::format(f).is_some_and(|f| f.id != "template"),
|
||||
// Override Save gives the step a native file name; else its own path names the format.
|
||||
None if redirected => true,
|
||||
None => path.and_then(super::format_for_name).is_none_or(|f| f.id != "template"),
|
||||
};
|
||||
format_ok && (redirected || path.is_some())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: &Run<'_>) -> Result<Value> {
|
||||
use super::{absolute_path, may_read};
|
||||
@@ -145,6 +227,18 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
|
||||
if names.len() > MAX_BATCH_FILES {
|
||||
return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets")));
|
||||
}
|
||||
let redirected = run.override_save && run.dest_folder.is_some();
|
||||
// A recorded save with a file to write gives the document a file of its own before Save and Close.
|
||||
if run.destination == "saveAndClose" && !run.steps.iter().any(|c| retargeting_save(c, redirected)) {
|
||||
if st.path.is_none() {
|
||||
return Err(bad(cmd, "the document has never been saved"));
|
||||
}
|
||||
// `save_plan` writes no file for a document converted from an older version or restored by
|
||||
// Data Recovery.
|
||||
if st.converted || st.recovered {
|
||||
return Err(bad(cmd, "save the document with Save As before Save and Close"));
|
||||
}
|
||||
}
|
||||
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
|
||||
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
|
||||
let steps = filter_steps(run.steps, true, false);
|
||||
@@ -1292,6 +1386,213 @@ mod tests {
|
||||
assert_eq!(file_names(&dest), ["Untitled_A-B-3.vectorcraft", "Untitled_a-b-2.vectorcraft", "Untitled_a-b.vectorcraft"], "{r}");
|
||||
}
|
||||
|
||||
/// A saved document with a text object bound to `Name` and two data sets, `A` and `B`.
|
||||
fn saved_with_two_data_sets(path: &std::path::Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "A"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Name", "ids": [id]})).unwrap();
|
||||
s.execute("dataset.capture", &json!({"name": "A"})).unwrap();
|
||||
s.execute("text.setText", &json!({"ids": [id], "text": "B"})).unwrap();
|
||||
s.execute("dataset.capture", &json!({"name": "B"})).unwrap();
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn save_and_close_over_data_sets(s: &mut Session) -> Result<Value> {
|
||||
s.execute(
|
||||
"action.batch",
|
||||
&json!({"source": "datasets", "destination": "saveAndClose", "commands": [{"command": "object.unlockAll", "params": {}}]}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_save_and_close_over_data_sets_saves_each_over_the_template_and_warns() {
|
||||
let path = tmp("save-close-sets").join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
std::fs::write(&path, b"stale").unwrap();
|
||||
let r = save_and_close_over_data_sets(&mut s).unwrap();
|
||||
assert_eq!((r["count"].as_u64(), r["failed"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}");
|
||||
assert_ne!(std::fs::read(&path).unwrap(), b"stale", "the template's file is saved over");
|
||||
assert_eq!(file_names(path.parent().unwrap()), ["template.vectorcraft"], "{r}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.variables.active_dataset.as_deref(), Some("B"), "the last data set is applied");
|
||||
assert_eq!(st.path.as_deref(), Some(path.to_string_lossy().as_ref()), "the template stays open");
|
||||
assert!(!st.is_dirty(), "the last data set is saved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_warns_when_a_recorded_save_writes_one_file_for_every_data_set() {
|
||||
let path = tmp("recorded-save-sets").join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
let save = json!([{"command": "document.save", "params": {}}]);
|
||||
let r = s.execute("action.batch", &json!({"source": "datasets", "commands": save})).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}");
|
||||
let dest = tmp("recorded-save-dest");
|
||||
let p = json!({"source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(), "commands": save});
|
||||
let r = s.execute("action.batch", &p).unwrap();
|
||||
assert!(r.get("warning").is_none(), "Override Save points each save into the folder: {r}");
|
||||
let unlock = json!({"source": "datasets", "commands": [{"command": "object.unlockAll", "params": {}}]});
|
||||
let r = s.execute("action.batch", &unlock).unwrap();
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_save_and_close_after_a_redirected_save_writes_each_data_set_to_its_own_file() {
|
||||
let save_close = |dest: &std::path::Path| {
|
||||
json!({
|
||||
"source": "datasets",
|
||||
"destination": "saveAndClose",
|
||||
"destinationFolder": dest.to_string_lossy(),
|
||||
"commands": [{"command": "document.save", "params": {}}]
|
||||
})
|
||||
};
|
||||
let path = tmp("redirected-save-close").join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let dest = tmp("redirected-save-close-dest");
|
||||
let p = save_close(&dest);
|
||||
let mut kept = p.clone();
|
||||
kept["overrideSave"] = json!(false);
|
||||
assert!(batch_overwrites_one_file(&s, &kept), "without Override Save the save stays on the template");
|
||||
let r = s.execute("action.batch", &p).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
assert_eq!(file_names(&dest), ["template_A.vectorcraft", "template_B.vectorcraft"], "{r}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the template's file stays as it was");
|
||||
// A document never saved gets its files from the redirected save too.
|
||||
let mut unsaved = with_data_sets(&["a", "b"]);
|
||||
let dest = tmp("redirected-save-close-unsaved");
|
||||
let r = unsaved.execute("action.batch", &save_close(&dest)).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
assert_eq!(file_names(&dest), ["Untitled_a.vectorcraft", "Untitled_b.vectorcraft"], "{r}");
|
||||
// A template save writes a copy: Save and Close still saves over the document's own file.
|
||||
let mut template = save_close(&dest);
|
||||
template["commands"] = json!([{"command": "document.save", "params": {"format": "template"}}]);
|
||||
assert!(batch_overwrites_one_file(&s, &template), "{template}");
|
||||
let mut never = with_data_sets(&["a", "b"]);
|
||||
let msg = never.execute("action.batch", &template).unwrap_err().to_string();
|
||||
assert!(msg.ends_with("the document has never been saved"), "{msg}");
|
||||
// A recorded Save As with its own path gives a never-saved document its file, the same one
|
||||
// for every data set.
|
||||
let one = tmp("save-as-then-close").join("one.vectorcraft");
|
||||
let p = json!({
|
||||
"source": "datasets",
|
||||
"destination": "saveAndClose",
|
||||
"commands": [{"command": "file.saveAs", "params": {"path": one.to_string_lossy()}}]
|
||||
});
|
||||
let r = never.execute("action.batch", &p).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}");
|
||||
assert!(one.exists(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_file_rule_covers_save_and_close_and_steps_left_in_place() {
|
||||
let saved = saved_with_two_data_sets(&tmp("one-file-rule").join("template.vectorcraft"));
|
||||
let unsaved = with_data_sets(&["a"]);
|
||||
let with = |extra: Value| {
|
||||
let mut p = json!({"source": "datasets", "commands": [{"command": "document.export", "params": {"path": "/x/a.png"}}]});
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
batch_overwrites_one_file(&saved, &p)
|
||||
};
|
||||
assert!(with(json!({})), "an export with its own path");
|
||||
assert!(!with(json!({"destination": "folder", "destinationFolder": "/out"})));
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "overrideExport": false})));
|
||||
assert!(!with(json!({"destination": "folder", "destinationFolder": "/out", "overrideSave": false})));
|
||||
assert!(!with(json!({"source": "folder"})), "a folder source opens a file per pass");
|
||||
assert!(with(json!({"destination": "saveAndClose", "commands": [{"command": "object.unlockAll"}]})));
|
||||
let saved_as = json!({"commands": [{"command": "file.saveAs", "params": {"path": "/x/a.svg"}}]});
|
||||
assert!(with(saved_as.clone()));
|
||||
assert!(!with(json!({"destination": "folder", "destinationFolder": "/out", "commands": saved_as["commands"]})));
|
||||
assert!(!with(json!({"commands": [{"command": "file.saveAs", "params": {}}]})), "no path: the data comes back");
|
||||
assert!(!with(json!({"commands": [{"command": "document.export", "params": {"format": "png"}}]})), "no path: the data comes back");
|
||||
let copy = json!([{"command": "file.saveCopy", "params": {"path": "/x/a.vectorcraft"}}]);
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": copy})), "Override Save leaves copies alone");
|
||||
let save = |format: Option<&str>| {
|
||||
let params = format.map_or(json!({}), |f| json!({"format": f}));
|
||||
json!({"source": "datasets", "commands": [{"command": "document.save", "params": params}]})
|
||||
};
|
||||
assert!(batch_overwrites_one_file(&saved, &save(None)), "the document's own file");
|
||||
assert!(batch_overwrites_one_file(&saved, &save(Some("vectorcraft"))), "the document's own format");
|
||||
assert!(!batch_overwrites_one_file(&unsaved, &save(None)), "a document never saved has no file to write");
|
||||
assert!(!batch_overwrites_one_file(&saved, &save(Some("svg"))), "another format without a path: the data comes back");
|
||||
assert!(!with(json!({"commands": [{"command": "file.saveCopy", "params": {"folder": "/x"}}]})), "a folder alone: the data comes back");
|
||||
let screens = json!([{"command": "document.exportForScreens", "params": {"folder": "/x"}}]);
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": screens})), "Override Export leaves its folder");
|
||||
assert!(!with(json!({"commands": [{"command": "document.exportForScreens", "params": {}}]})));
|
||||
let preset = json!([{"command": "document.exportForScreens", "params": {"exportPreset": "Logo Package"}}]);
|
||||
assert!(!with(json!({"commands": preset})), "a preset without a folder: the data comes back");
|
||||
for id in ["document.exportPdf", "document.exportEps", "document.exportDxf", "document.exportForWeb", "document.exportForOffice"] {
|
||||
let step = json!([{"command": id, "params": {"path": "/x/a.out"}}]);
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": step})), "{id} keeps its path");
|
||||
assert!(!with(json!({"commands": [{"command": id, "params": {}}]})), "{id} without a path: the data comes back");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_refuses_save_and_close_over_data_sets_of_a_converted_or_recovered_document() {
|
||||
for converted in [true, false] {
|
||||
let path = tmp(if converted { "converted-sets" } else { "recovered-sets" }).join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let (active, revision) = {
|
||||
let st = s.doc_mut().unwrap();
|
||||
if converted {
|
||||
st.converted = true;
|
||||
} else {
|
||||
st.recovered = true;
|
||||
}
|
||||
(st.doc.variables.active_dataset.clone(), st.revision)
|
||||
};
|
||||
let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string();
|
||||
assert!(msg.ends_with("save the document with Save As before Save and Close"), "{msg}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is not written");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected");
|
||||
assert_eq!(st.revision, revision, "no step runs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_refuses_save_and_close_over_data_sets_of_an_unsaved_document() {
|
||||
let mut s = with_data_sets(&["a", "b"]);
|
||||
let (active, revision) = {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.variables.active_dataset.clone(), st.revision)
|
||||
};
|
||||
let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string();
|
||||
assert!(msg.ends_with("the document has never been saved"), "{msg}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected");
|
||||
assert_eq!(st.revision, revision, "no step runs");
|
||||
assert!(st.path.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_save_and_close_saves_and_closes_each_source_file() {
|
||||
let src = tmp("save-close-src");
|
||||
let a = write_svg(&src, "a.svg", "#f00");
|
||||
let before = std::fs::read(&a).unwrap();
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute(
|
||||
"action.batch",
|
||||
&json!({"folder": src.to_string_lossy(), "destination": "saveAndClose", "commands": [{"command": "object.unlockAll", "params": {}}]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_ne!(std::fs::read(&a).unwrap(), before, "the source file is saved over");
|
||||
assert_eq!(file_names(&src), ["a.svg"], "{r}");
|
||||
assert!(s.doc().is_err(), "the source file is closed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_refuses_nesting_and_empty_commands() {
|
||||
let mut s = Session::new();
|
||||
|
||||
Loaded 100 of 603 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user